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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
use anyhow::Result;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use tokio::runtime::Runtime;

use crate::cli::Args;
use crate::commands::Command;
use crate::config::Config;
use crate::ffplay::VlcController;
use crate::tui::{TuiApp, TuiManager};
use crate::types::{MediaSource, PlayerState, TuiLogger};
use crate::utils;
use crate::playlists::PlaylistsManager;

pub struct App {
    args: Args,
    config: Config,
}

impl App {
    pub fn new(args: Args) -> Result<Self> {
        // Validate arguments
        args.validate().map_err(|e| anyhow::anyhow!("Invalid arguments: {}", e))?;

        // Load configuration
        let config = Config::load()?;

        Ok(Self {
            args,
            config,
        })
    }

    pub fn run(&mut self) -> Result<()> {
        // Create channels for communication between threads
        let (command_tx, command_rx) = mpsc::channel::<Command>();
        let (state_tx, state_rx) = mpsc::channel::<PlayerState>();
        let (log_tx, log_rx) = mpsc::channel::<Command>();

        // Create logger for main thread
        let logger = TuiLogger::new(log_tx.clone());
        logger.info("Application starting");
        logger.debug("Channels created successfully");

        // Initialize VLC controller (starts VLC automatically)
        logger.debug("Starting VLC and initializing HTTP controller");
        let mut vlc = VlcController::new(Some("127.0.0.1"), Some(8080))?;
        logger.info("VLC started and HTTP controller initialized");

        // Create async runtime for VLC operations
        let rt = Runtime::new()?;

        // Apply initial settings immediately since password is auto-set
        logger.debug("Applying initial settings");
        if let Some(volume) = self.args.volume {
            logger.debug(&format!("Setting initial volume to: {}", volume));
            if let Err(e) = rt.block_on(vlc.set_volume(volume)) {
                logger.error(&format!("Failed to set initial volume: {}", e));
            }
        } else {
            logger.debug(&format!("Setting default volume to: {}", self.config.default_volume));
            if let Err(e) = rt.block_on(vlc.set_volume(self.config.default_volume)) {
                logger.error(&format!("Failed to set default volume: {}", e));
            }
        }

        if self.args.muted {
            logger.debug("Setting initial mute state");
            if let Err(e) = rt.block_on(vlc.mute()) {
                logger.error(&format!("Failed to set initial mute: {}", e));
            }
        }

        logger.debug(&format!("Setting initial speed to: {}", self.args.speed));
        if let Err(e) = rt.block_on(vlc.set_speed(self.args.speed)) {
            logger.error(&format!("Failed to set initial speed: {}", e));
        }

        // Set fullscreen preference
        if !self.args.windowed && self.config.fullscreen_by_default {
            logger.debug("Setting fullscreen mode");
            if let Err(e) = rt.block_on(vlc.toggle_fullscreen()) {
                logger.error(&format!("Failed to set fullscreen: {}", e));
            }
        }

        // Load initial media if provided
        if let Some(ref media) = self.args.media {
            logger.info(&format!("Loading initial media: {}", media));
            let source = if utils::is_youtube_url(media) {
                logger.info("Media identified as YouTube URL, downloading...");
                match crate::youtube::download_youtube_content_with_logger(media, Some(logger.clone())) {
                    Ok(downloaded_source) => {
                        logger.info("YouTube content downloaded successfully");
                        downloaded_source
                    }
                    Err(e) => {
                        logger.error(&format!("Failed to download YouTube content: {}", e));
                        // Fall back to direct URL
                        MediaSource::Url(media.clone())
                    }
                }
            } else if utils::is_url(media) {
                logger.debug("Media identified as URL");
                MediaSource::Url(media.clone())
            } else {
                logger.debug("Media identified as local file");
                MediaSource::LocalFile(media.clone())
            };
            
            if let Err(e) = rt.block_on(vlc.load_media(&source)) {
                logger.error(&format!("Failed to load initial media: {}", e));
            } else {
                logger.info("Initial media loaded successfully");
            }
        }

        logger.debug("Setting up TUI");
        // Setup TUI
        let terminal = TuiManager::setup()?;
        let mut tui_app = TuiApp::new(command_tx.clone(), state_rx, log_rx);

        logger.debug("Starting TUI thread");
        // Start TUI thread
        let tui_handle = thread::spawn(move || {
            tui_app.run(terminal)
        });

        logger.info("Starting main player loop");
        // Main player loop - handle commands in the main thread
    let mut running = true;
        let mut command_count = 0;
        let mut last_state_update = std::time::Instant::now();
        let mut playlist_playback: Option<(String, usize)> = None; // (playlist_id, index)
    let mut at_end_last_tick = false;
        
        while running {
            // Try to receive a command with a timeout
            match command_rx.recv_timeout(Duration::from_millis(100)) {
                Ok(command) => {
                    command_count += 1;
                    if !matches!(command, Command::UpdateState) {
                        logger.debug(&format!("Main thread received command #{}: {:?}", command_count, command));
                    }

                    // Track playlist playback state for loop logic
                    if let Command::PlaylistPlay { playlist_id, index } = &command {
                        playlist_playback = Some((playlist_id.clone(), *index));
                    }
                    if let Command::Open(_) | Command::Load(_) = &command {
                        playlist_playback = None; // manual open cancels playlist mode
                    }

                    match Self::handle_command(command, &mut vlc, &rt, &self.config, &self.args, &state_tx, &logger, &log_tx) {
                        Ok(should_quit) => {
                            if should_quit {
                                logger.info("Main thread received quit signal");
                                running = false;
                            }
                        }
                        Err(e) => {
                            logger.error(&format!("Error handling command: {}", e));
                        }
                    }
                }
                Err(mpsc::RecvTimeoutError::Timeout) => {
                    // No command received, send state update periodically
                    if last_state_update.elapsed() >= Duration::from_millis(500) {
                        // Send UpdateState command to ensure any listeners are notified
                        if command_tx.send(Command::UpdateState).is_err() {
                            logger.warn("Failed to send UpdateState command - channel closed");
                        }
                        
                        let state = rt.block_on(vlc.get_state());
                        if state_tx.send(state.clone()).is_err() {
                            logger.warn("Failed to send state update - channel closed");
                            running = false;
                        }
                        last_state_update = std::time::Instant::now();

                        // Auto loop/advance behavior
                        if let Some(dur) = state.media_info.duration {
                            let pos = state.media_info.position;
                            let near_end = dur > 0.0 && (dur - pos) <= 2.0;

                            if near_end && !at_end_last_tick {
                                if let Some((pid, idx)) = playlist_playback.clone() {
                                    // Advance to next item in playlist
                                    let mut mgr = PlaylistsManager::new_or_default();
                                    let next: Option<(usize, crate::playlists::PlaylistItem)> = {
                                        if let Some(pl) = mgr.get_mut(&pid) {
                                            if pl.items.is_empty() { None } else {
                                                let next_idx = (idx + 1) % pl.items.len();
                                                let item = pl.items[next_idx].clone();
                                                pl.increment_play(&item.id);
                                                Some((next_idx, item))
                                            }
                                        } else { None }
                                    };
                                    if let Some((next_idx, item)) = next {
                                        let _ = mgr.save();
                                        let _ = mgr.reload();
                                        let _ = log_tx.send(Command::PlaylistReload);
                                        let source = Self::path_to_media_source(&item.url, &logger)?;
                                        if let Err(e) = rt.block_on(vlc.load_media(&source)) {
                                            logger.error(&format!("Failed to auto-advance playlist: {}", e));
                                        } else {
                                            playlist_playback = Some((pid.clone(), next_idx));
                                            logger.info(&format!("Advanced to next playlist item: {}", item.name));
                                            let _ = log_tx.send(Command::PlaylistNowPlaying { playlist_id: pid.clone(), item_id: item.id.clone() });
                                        }
                                    }
                                } else {
                                    // Single-item loop: seek to start
                                    if pos > 0.1 {
                                        if let Err(e) = rt.block_on(vlc.seek(-pos)) {
                                            logger.warn(&format!("Failed to loop current item: {}", e));
                                        } else {
                                            logger.info("Looped current item to start");
                                        }
                                    }
                                }
                            }
                            at_end_last_tick = near_end;
                        } else {
                            at_end_last_tick = false;
                        }
                    }
                }
                Err(mpsc::RecvTimeoutError::Disconnected) => {
                    logger.warn("Command channel disconnected");
                    running = false;
                }
            }
        }

        logger.info("Main loop ending, cleaning up VLC");
        if let Err(e) = rt.block_on(vlc.quit()) {
            logger.error(&format!("Error during VLC cleanup: {}", e));
        } else {
            logger.info("VLC cleanup completed successfully");
        }

        logger.debug("Signaling TUI thread to quit");
        // Signal TUI thread to quit through the log channel
        if let Err(e) = log_tx.send(Command::Quit) {
            logger.warn(&format!("Failed to send quit signal to TUI thread: {}", e));
        } else {
            logger.debug("Quit signal sent to TUI thread");
        }

        logger.debug("Waiting for TUI thread to finish");
        // Wait for TUI thread to finish with a timeout
        let join_timeout = Duration::from_secs(5);
        let join_start = std::time::Instant::now();
        
        // Use a channel to handle the join with timeout
        let (join_tx, join_rx) = mpsc::channel();
        let join_handle_for_timeout = thread::spawn(move || {
            let result = tui_handle.join().map_err(|_| anyhow::anyhow!("TUI thread panicked"));
            let _ = join_tx.send(result);
        });
        
        let tui_result = match join_rx.recv_timeout(join_timeout) {
            Ok(result) => {
                logger.debug(&format!("TUI thread finished after {:?}", join_start.elapsed()));
                result?
            }
            Err(mpsc::RecvTimeoutError::Timeout) => {
                logger.error(&format!("TUI thread did not respond within {:?}, forcing cleanup", join_timeout));
                // Force cleanup and continue - the TUI thread will be terminated when the process exits
                TuiManager::cleanup()?;
                return Ok(());
            }
            Err(mpsc::RecvTimeoutError::Disconnected) => {
                logger.error("TUI join channel disconnected unexpectedly");
                return Err(anyhow::anyhow!("TUI join channel disconnected"));
            }
        };
        
        // Clean up the timeout thread
        let _ = join_handle_for_timeout.join();

        logger.debug("Starting cleanup");
        // Cleanup
        TuiManager::cleanup()?;

        // Handle TUI result
        tui_result?;

        // Save configuration
        logger.debug("Saving configuration");
        if let Err(e) = self.config.save() {
            logger.warn(&format!("Failed to save configuration: {}", e));
        } else {
            logger.info("Configuration saved successfully");
        }

        logger.info(&format!("Application shutdown complete after processing {} commands", command_count));
        Ok(())
    }

    fn handle_command(
        command: Command,
        vlc: &mut VlcController,
        rt: &Runtime,
        config: &Config,
        _args: &Args,
        state_tx: &mpsc::Sender<PlayerState>,
        logger: &TuiLogger,
        log_tx: &mpsc::Sender<Command>,
    ) -> Result<bool> {
        if !matches!(command, Command::UpdateState) {
            logger.debug(&format!("Handling command: {:?}", command));
        }
        let mut suppress_state = false;
        match command {
            Command::Quit => {
                logger.info("Quit command received");
                return Ok(true);
            }
            
            // Basic playback controls
            Command::Play => {
                logger.debug("Command: play");
                rt.block_on(vlc.play_pause())?;
            }
            Command::Pause => {
                logger.debug("Command: pause");
                rt.block_on(vlc.play_pause())?;
            }
            Command::Toggle => {
                logger.debug("Command: toggle play/pause");
                rt.block_on(vlc.play_pause())?;
            }
            Command::Stop => {
                logger.debug("Command: stop");
                rt.block_on(vlc.stop())?;
                let _ = log_tx.send(Command::PlaylistClearNowPlaying);
            }
            
            // Volume controls
            Command::VolumeUp => {
                let current_state = rt.block_on(vlc.get_state());
                let old_volume = current_state.media_info.volume;
                let new_volume = (current_state.media_info.volume + config.ui.volume_step).min(100.0);
                logger.debug(&format!("Volume up: {} -> {}", old_volume, new_volume));
                rt.block_on(vlc.set_volume(new_volume))?;
            }
            Command::VolumeDown => {
                let current_state = rt.block_on(vlc.get_state());
                let old_volume = current_state.media_info.volume;
                let new_volume = (current_state.media_info.volume - config.ui.volume_step).max(0.0);
                logger.debug(&format!("Volume down: {} -> {}", old_volume, new_volume));
                rt.block_on(vlc.set_volume(new_volume))?;
            }
            Command::Volume(volume) => {
                logger.debug(&format!("Command: set volume to {}", volume));
                rt.block_on(vlc.set_volume(volume))?;
            }
            Command::Mute => {
                logger.debug("Command: mute");
                rt.block_on(vlc.mute())?;
            }
            Command::Unmute => {
                logger.debug("Command: unmute");
                // Toggle mute if currently muted
                let current_state = rt.block_on(vlc.get_state());
                if current_state.media_info.muted {
                    rt.block_on(vlc.mute())?;
                }
            }
            
            // Seeking controls
            Command::SeekForward => {
                logger.debug(&format!("Seek forward: {}s", config.ui.seek_step));
                rt.block_on(vlc.seek(config.ui.seek_step))?;
            }
            Command::SeekBackward => {
                logger.debug(&format!("Seek backward: -{}s", config.ui.seek_step));
                rt.block_on(vlc.seek(-config.ui.seek_step))?;
            }
            Command::Seek(seconds) => {
                logger.debug(&format!("Command: seek {} seconds", seconds));
                rt.block_on(vlc.seek(seconds))?;
            }
            Command::SeekTo(position) => {
                logger.debug(&format!("Command: seek to position {} seconds", position));
                rt.block_on(vlc.seek(position))?; // Note: this should be absolute seek
            }
            Command::Forward(seconds) => {
                logger.debug(&format!("Command: forward {} seconds", seconds));
                rt.block_on(vlc.seek(seconds))?;
            }
            Command::Backward(seconds) => {
                logger.debug(&format!("Command: backward {} seconds", seconds));
                rt.block_on(vlc.seek(-seconds))?;
            }
            
            // Speed controls
            Command::SpeedUp => {
                let current_state = rt.block_on(vlc.get_state());
                let old_speed = current_state.media_info.speed;
                let new_speed = (current_state.media_info.speed + config.ui.speed_step).min(5.0);
                logger.debug(&format!("Speed up: {}x -> {}x", old_speed, new_speed));
                rt.block_on(vlc.set_speed(new_speed))?;
            }
            Command::SpeedDown => {
                let current_state = rt.block_on(vlc.get_state());
                let old_speed = current_state.media_info.speed;
                let new_speed = (current_state.media_info.speed - config.ui.speed_step).max(0.1);
                logger.debug(&format!("Speed down: {}x -> {}x", old_speed, new_speed));
                rt.block_on(vlc.set_speed(new_speed))?;
            }
            Command::Speed(speed) => {
                logger.debug(&format!("Command: set speed to {}", speed));
                rt.block_on(vlc.set_speed(speed))?;
            }
            Command::SpeedReset | Command::ResetSpeed => {
                logger.debug("Command: reset speed to 1.0x");
                rt.block_on(vlc.set_speed(1.0))?;
            }
            
            // Display controls
            Command::ToggleFullscreen => {
                logger.debug("Command: toggle fullscreen");
                rt.block_on(vlc.toggle_fullscreen())?;
            }
            Command::Fullscreen => {
                logger.debug("Command: enter fullscreen");
                rt.block_on(vlc.toggle_fullscreen())?; // Should check if already fullscreen
            }
            Command::Windowed => {
                logger.debug("Command: exit fullscreen");
                rt.block_on(vlc.toggle_fullscreen())?; // Should check if in fullscreen
            }
            Command::ToggleLoop => {
                logger.debug("Command: toggle loop");
                rt.block_on(vlc.toggle_loop())?;
            }
            Command::Loop => {
                logger.debug("Command: toggle loop (alias)");
                rt.block_on(vlc.toggle_loop())?;
            }
            
            // Media loading - use Open and Load commands only
            Command::Open(ref path) | Command::Load(ref path) => {
                let source = Self::path_to_media_source(path, logger)?;
                Self::load_media_source(vlc, rt, &source, logger)?;
                let _ = log_tx.send(Command::PlaylistClearNowPlaying);
            }
            
            // Connection commands
            Command::TestConnection => {
                logger.debug("Command: test connection");
                match rt.block_on(vlc.test_connection()) {
                    Ok(connected) => {
                        if connected {
                            logger.info("VLC connection test successful");
                        } else {
                            logger.warn("VLC connection test failed");
                        }
                    }
                    Err(e) => {
                        logger.error(&format!("VLC connection test error: {}", e));
                    }
                }
                let state = rt.block_on(vlc.get_state());
                let _ = state_tx.send(state);
                suppress_state = true;
            }
            
            // Application commands
            Command::ShowHelp | Command::HideHelp | Command::Help => {
                // These are handled by the TUI, no VLC action needed
                logger.debug("Help command - handled by TUI");
            }
            
            // Internal commands
            Command::UpdateState => {
                // Update and send current state
                let state = rt.block_on(vlc.get_state());
                let _ = state_tx.send(state);
                suppress_state = true;
            }
            Command::Log(_) => {
                // Log entries are handled by the logger system, no action needed
                suppress_state = true;
            }
            Command::ExecuteCommand(ref command_str) => {
                // Handle special export/import commands with paths
                if let Some(path_str) = command_str.strip_prefix("export_to ") {
                    let export_path = std::path::PathBuf::from(path_str);
                    
                    logger.info(&format!("Config export command with custom path: {:?}", export_path));
                    use crate::config_manager::ConfigManager;
                    
                    match ConfigManager::new() {
                        Ok(manager) => {
                            match manager.export_to(&export_path) {
                                Ok(()) => {
                                    logger.info(&format!("Configuration exported to: {:?}", export_path));
                                }
                                Err(e) => {
                                    logger.error(&format!("Failed to export configuration: {}", e));
                                }
                            }
                        }
                        Err(e) => {
                            logger.error(&format!("Failed to create config manager: {}", e));
                        }
                    }
                } else if let Some(path_str) = command_str.strip_prefix("import_from ") {
                    let import_path = std::path::PathBuf::from(path_str);
                    
                    logger.info(&format!("Config import command with custom path: {:?}", import_path));
                    use crate::config_manager::ConfigManager;
                    
                    if !import_path.exists() {
                        logger.error(&format!("Config import file not found: {:?}", import_path));
                        return Ok(false);
                    }
                    
                    match ConfigManager::new() {
                        Ok(manager) => {
                            match manager.import_from(&import_path) {
                                Ok(()) => {
                                    logger.info(&format!("Configuration imported from: {:?}", import_path));
                                }
                                Err(e) => {
                                    logger.error(&format!("Failed to import configuration: {}", e));
                                }
                            }
                        }
                        Err(e) => {
                            logger.error(&format!("Failed to create config manager: {}", e));
                        }
                    }
                } else {
                    // Parse and execute the command string normally
                    match crate::commands::parse_command(command_str) {
                        Ok(parsed_command) => {
                            logger.debug(&format!("Executing parsed command: {:?}", parsed_command));
                            return Self::handle_command(parsed_command, vlc, rt, config, _args, state_tx, logger, log_tx);
                        }
                        Err(e) => {
                            logger.error(&format!("Failed to parse command '{}': {}", command_str, e));
                        }
                    }
                }
            }
            
            // Commands that need implementation
            Command::Connect(ref host, ref port) => {
                logger.info(&format!("Connect command not implemented: {}:{:?}", host, port));
            }
            Command::Disconnect => {
                logger.info("Disconnect command not implemented");
            }
            Command::Config => {
                logger.info("Config command received, forwarding to TUI");
                if let Err(e) = log_tx.send(Command::ShowConfig) {
                    logger.error(&format!("Failed to send ShowConfig command to TUI: {}", e));
                }
            }
            Command::Save => {
                logger.info("Save command received, saving configuration");
                use crate::config_manager::ConfigManager;
                match ConfigManager::new() {
                    Ok(manager) => {
                        match manager.sync() {
                            Ok(()) => {
                                logger.info("Configuration saved successfully");
                            }
                            Err(e) => {
                                logger.error(&format!("Failed to save configuration: {}", e));
                            }
                        }
                    }
                    Err(e) => {
                        logger.error(&format!("Failed to create config manager: {}", e));
                    }
                }
            }
            Command::Reload => {
                logger.info("Reload command received, reloading configuration");
                match Config::load() {
                    Ok(_new_config) => {
                        logger.info("Configuration reloaded successfully");
                        // Note: We can't modify the config in the current structure
                        // This would require restructuring to allow config updates
                        logger.warn("Config reload loaded but cannot update runtime config");
                    }
                    Err(e) => {
                        logger.error(&format!("Failed to reload configuration: {}", e));
                    }
                }
            }
            Command::ShowConfig => {
                logger.info("Show config command received, forwarding to TUI");
                if let Err(e) = log_tx.send(Command::ShowConfig) {
                    logger.error(&format!("Failed to send ShowConfig command to TUI: {}", e));
                }
            }
            Command::HideConfig => {
                logger.info("Hide config command received, forwarding to TUI");
                if let Err(e) = log_tx.send(Command::HideConfig) {
                    logger.error(&format!("Failed to send HideConfig command to TUI: {}", e));
                }
            }
            Command::ConfigNext => {
                logger.info("Config next command received (handled by TUI)");
            }
            Command::ConfigPrev => {
                logger.info("Config prev command received (handled by TUI)");
            }
            Command::ConfigEdit => {
                logger.info("Config edit command received (handled by TUI)");
            }
            Command::ConfigReset => {
                logger.info("Config reset command received, resetting configuration to defaults");
                use crate::config_manager::ConfigManager;
                match ConfigManager::new() {
                    Ok(manager) => {
                        match manager.reset_all() {
                            Ok(()) => {
                                logger.info("Configuration reset to defaults successfully");
                            }
                            Err(e) => {
                                logger.error(&format!("Failed to reset configuration: {}", e));
                            }
                        }
                    }
                    Err(e) => {
                        logger.error(&format!("Failed to create config manager: {}", e));
                    }
                }
            }
            Command::ConfigExport => {
                logger.info("Config export command received");
                use crate::config_manager::ConfigManager;
                use std::path::PathBuf;
                
                // For now, export to a default location
                let export_path = dirs::home_dir()
                    .unwrap_or_else(|| PathBuf::from("."))
                    .join("bckplayer_config_export.json");
                    
                match ConfigManager::new() {
                    Ok(manager) => {
                        match manager.export_to(&export_path) {
                            Ok(()) => {
                                logger.info(&format!("Configuration exported to: {:?}", export_path));
                            }
                            Err(e) => {
                                logger.error(&format!("Failed to export configuration: {}", e));
                            }
                        }
                    }
                    Err(e) => {
                        logger.error(&format!("Failed to create config manager: {}", e));
                    }
                }
            }
            Command::ConfigImport => {
                logger.info("Config import command received");
                use crate::config_manager::ConfigManager;
                use std::path::PathBuf;
                
                // For now, import from a default location
                let import_path = dirs::home_dir()
                    .unwrap_or_else(|| PathBuf::from("."))
                    .join("bckplayer_config_export.json");
                    
                if !import_path.exists() {
                    logger.error(&format!("Config import file not found: {:?}", import_path));
                    return Ok(false);
                }
                
                match ConfigManager::new() {
                    Ok(manager) => {
                        match manager.import_from(&import_path) {
                            Ok(()) => {
                                logger.info(&format!("Configuration imported from: {:?}", import_path));
                            }
                            Err(e) => {
                                logger.error(&format!("Failed to import configuration: {}", e));
                            }
                        }
                    }
                    Err(e) => {
                        logger.error(&format!("Failed to create config manager: {}", e));
                    }
                }
            }
            
            // YouTube commands
            Command::YoutubeShowCache => {
                logger.info("Command: show YouTube cache statistics");
                match crate::youtube::YoutubeManager::new_with_logger(Some(logger.clone())) {
                    Ok(manager) => {
                        match manager.get_cache_stats() {
                            Ok(stats) => {
                                logger.info("YouTube Cache Stats:");
                                logger.info(&format!("  Files: {}", stats.total_files));
                                logger.info(&format!("  Size: {:.2} MB / {:.2} MB ({:.1}%)", 
                                    stats.total_size_mb, stats.max_size_mb, stats.usage_percentage));
                            }
                            Err(e) => {
                                logger.error(&format!("Failed to get cache stats: {}", e));
                            }
                        }
                    }
                    Err(e) => {
                        logger.error(&format!("Failed to create YouTube manager: {}", e));
                    }
                }
                suppress_state = true;
            }
            Command::YoutubeClearCache => {
                logger.info("Command: clear YouTube cache");
                match crate::youtube::YoutubeManager::new_with_logger(Some(logger.clone())) {
                    Ok(mut manager) => {
                        match manager.clear_cache() {
                            Ok(()) => {
                                logger.info("YouTube cache cleared successfully");
                            }
                            Err(e) => {
                                logger.error(&format!("Failed to clear cache: {}", e));
                            }
                        }
                    }
                    Err(e) => {
                        logger.error(&format!("Failed to create YouTube manager: {}", e));
                    }
                }
                suppress_state = true;
            }
            Command::YoutubeDownload(ref url) => {
                logger.info(&format!("Command: download YouTube content from {}", url));
                match crate::youtube::download_youtube_content_with_logger(url, Some(logger.clone())) {
                    Ok(source) => {
                        logger.info(&format!("Downloaded YouTube content: {:?}", source));
                        // Optionally load the downloaded content
                        if let Err(e) = rt.block_on(vlc.load_media(&source)) {
                            logger.error(&format!("Failed to load downloaded content: {}", e));
                        }
                    }
                    Err(e) => {
                        logger.error(&format!("Failed to download YouTube content: {}", e));
                    }
                }
            }

            // Playlists
            Command::PlaylistAdd { name } => {
                let mut mgr = PlaylistsManager::new_or_default();
                // Limit the mutable borrow scope and clone needed data
                let added_name = {
                    let p = mgr.add_playlist(name);
                    p.name.clone()
                };
                let _ = mgr.save();
                let _ = mgr.reload();
                let _ = log_tx.send(Command::PlaylistReload);
                logger.info(&format!("Playlist added: {}", added_name));
            }
            Command::PlaylistDelete { playlist_id } => {
                let mut mgr = PlaylistsManager::new_or_default();
                mgr.remove_playlist(&playlist_id);
                let _ = mgr.save();
                let _ = mgr.reload();
                let _ = log_tx.send(Command::PlaylistReload);
                logger.info(&format!("Playlist deleted: {}", playlist_id));
            }
            Command::PlaylistItemAdd { playlist_id, item } => {
                let mut mgr = PlaylistsManager::new_or_default();
                let playlist_name = {
                    if let Some(pl) = mgr.get_mut(&playlist_id) {
                        pl.add_item(item);
                        pl.sort_items();
                        Some(pl.name.clone())
                    } else { None }
                };
                let _ = mgr.save();
                let _ = mgr.reload();
                let _ = log_tx.send(Command::PlaylistReload);
                if let Some(name) = playlist_name {
                    logger.info(&format!("Item added to playlist: {}", name));
                } else {
                    logger.warn("Playlist not found for adding item");
                }
            }
            Command::PlaylistItemDelete { playlist_id, item_id } => {
                let mut mgr = PlaylistsManager::new_or_default();
                let playlist_name = {
                    if let Some(pl) = mgr.get_mut(&playlist_id) {
                        let name = pl.name.clone();
                        if pl.remove_item(&item_id) { Some(name) } else { None }
                    } else { None }
                };
                let _ = mgr.save();
                let _ = mgr.reload();
                let _ = log_tx.send(Command::PlaylistReload);
                if let Some(name) = playlist_name {
                    logger.info(&format!("Item removed from playlist: {}", name));
                }
            }
            Command::PlaylistPlay { playlist_id, index } => {
                let mut mgr = PlaylistsManager::new_or_default();
                let selected_item = {
                    if let Some(pl) = mgr.get_mut(&playlist_id) {
                        if let Some(item) = pl.items.get(index).cloned() {
                            pl.increment_play(&item.id);
                            Some(item)
                        } else { None }
                    } else { None }
                };
                if let Some(item) = selected_item {
                    let _ = mgr.save();
                    let _ = mgr.reload();
                    let _ = log_tx.send(Command::PlaylistReload);
                    // Load media
                    let source = Self::path_to_media_source(&item.url, logger)?;
                    Self::load_media_source(vlc, rt, &source, logger)?;
                    let _ = log_tx.send(Command::PlaylistNowPlaying { playlist_id, item_id: item.id });
                } else {
                    logger.warn("Playlist or item not found for play");
                }
            }
            Command::PlaylistReload => {
                // Nothing to do in app; TUI handles reload on its side
                logger.debug("Received PlaylistReload command (no-op in core)");
                suppress_state = true;
            }
            Command::PlaylistNowPlaying { .. } | Command::PlaylistClearNowPlaying => {
                // These are UI notifications only
                suppress_state = true;
            }
        }

        // Send updated state after command execution (except for special commands)
        if !suppress_state {
            let state = rt.block_on(vlc.get_state());
            let _ = state_tx.send(state);
        }

        Ok(false)
    }

    /// Helper function to convert a path string to a MediaSource
    fn path_to_media_source(path: &str, logger: &TuiLogger) -> Result<MediaSource> {
        let source = if utils::is_youtube_url(path) {
            logger.info(&format!("Loading YouTube URL: {}", path));
            match crate::youtube::download_youtube_content_with_logger(path, Some(logger.clone())) {
                Ok(downloaded_source) => {
                    logger.info("YouTube content downloaded successfully");
                    downloaded_source
                }
                Err(e) => {
                    logger.error(&format!("Failed to download YouTube content: {}", e));
                    // Fall back to direct URL
                    MediaSource::Url(path.to_string())
                }
            }
        } else if utils::is_url(path) {
            MediaSource::Url(path.to_string())
        } else {
            MediaSource::LocalFile(path.to_string())
        };
        Ok(source)
    }

    /// Helper function to load a MediaSource into VLC
    fn load_media_source(
        vlc: &mut VlcController,
        rt: &Runtime,
        source: &MediaSource,
        logger: &TuiLogger,
    ) -> Result<()> {
        logger.info(&format!("Loading media: {:?}", source));
        rt.block_on(vlc.load_media(source))?;
        Ok(())
    }
}