#!/usr/bin/env python3
"""
play and manage a song queue with shuffle, repeat, and more
"""
import sys
import os
import argparse
import random
import time
import threading
from pathlib import Path
from enum import Enum

# Handle imports for both package and standalone execution
try:
    from .player import AudioPlayer
    from .playlist import load_m3u_playlist
    from . import metadata
except ImportError:
    # Add parent directory to path for standalone execution
    sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    from core.player import AudioPlayer
    from core.playlist import load_m3u_playlist
    from core import metadata

# Debug mode - set to False to disable debug logging for efficiency
DEBUG_MODE = False

def debug_log(message):
    """
    Print debug message only if DEBUG_MODE is enabled.
    
    Args:
        message: Debug message to print.
    """
    if DEBUG_MODE:
        print(f"[DEBUG] {message}")

class RepeatMode(Enum):
    """Repeat modes for audio playback"""
    OFF = "off"
    TRACK = "track"
    QUEUE = "queue"

class QueueManager:
    """Manages audio playback queue with shuffle, repeat, and history tracking."""
    
    def __init__(self, songs=None):
        """Initialize QueueManager with a list of songs."""
        self.songs = songs or []
        self.current_index = 0
        self.repeat_mode = RepeatMode.OFF
        self.shuffle = False
        self.playback_history = []  # Global history for universal previous
        self.forward_queue = []  # Predicted future songs for shuffle
        self.forward_history = []  # Songs to return to when hitting next after previous
    
    def set_repeat_mode(self, mode):
        """Set repeat mode: "off", "track", or "queue". Mode changes preserve forward queue."""
        if isinstance(mode, str):
            mode = RepeatMode(mode.lower())
        
        old_mode = self.repeat_mode
        self.repeat_mode = mode
        
        debug_log(f"set_repeat_mode(): Changed from {old_mode.value} to {mode.value}, "
                 f"current: {self.current_index}, forward_queue: {len(self.forward_queue)} items")
        
        print(f"Repeat mode set to: {mode.value}")
    
    def set_shuffle_mode(self, enabled):
        """Set shuffle mode on/off. Mode changes preserve forward queue."""
        old_shuffle = self.shuffle
        self.shuffle = enabled
        effective = self.is_shuffle_effective()
        
        debug_log(f"set_shuffle_mode(): Changed from {old_shuffle} to {enabled}, "
                 f"effective: {effective}, forward_queue: {len(self.forward_queue)} items")
        
        print(f"Shuffle mode: {'ON' if enabled else 'OFF'}" + 
              (f" (disabled by repeat mode)" if enabled and not effective else ""))
    
    def is_shuffle_effective(self):
        """Check if shuffle is actively being used (only with repeat OFF)."""
        return self.shuffle and self.repeat_mode == RepeatMode.OFF
    
    def current_song(self):
        """Get the currently playing song."""
        if 0 <= self.current_index < len(self.songs):
            return self.songs[self.current_index]
        return None
    
    def _get_next_shuffle_song(self):
        """Get next song in shuffle mode using forward queue for consistency."""
        # If we have a forward queue, use it
        if self.forward_queue:
            return self.forward_queue[0]
        
        # Generate new forward queue with remaining unplayed songs
        recent_history = self.playback_history[-len(self.songs):] if len(self.playback_history) >= len(self.songs) else self.playback_history
        unplayed = [i for i in range(len(self.songs)) 
                   if recent_history.count(i) == 0 and i != self.current_index]
        
        if unplayed:
            # Shuffle unplayed songs and store as forward queue
            random.shuffle(unplayed)
            self.forward_queue = unplayed
            debug_log(f"_get_next_shuffle_song(): Generated forward_queue with {len(unplayed)} unplayed songs")
            return self.forward_queue[0]
        else:
            # All songs played recently, generate new random sequence
            all_indices = [i for i in range(len(self.songs)) if i != self.current_index]
            random.shuffle(all_indices)
            self.forward_queue = all_indices
            debug_log(f"_get_next_shuffle_song(): All played, generated new forward_queue with {len(all_indices)} songs")
            return self.forward_queue[0] if self.forward_queue else self.current_index
    
    def has_songs(self):
        """Check if there are songs in the queue."""
        return len(self.songs) > 0
    
    def next_track(self):
        """
        Move to next track. Prioritizes forward history (from previous button) over normal progression.
        Always adds current song to global history for universal previous functionality.
        Returns True if moved successfully, False if at end.
        """
        if not self.has_songs():
            return False
        
        # Check for forward history first (from previous button usage)
        if self.forward_history:
            self.playback_history.append(self.current_index)
            self.current_index = self.forward_history.pop()
            debug_log(f"next_track(): Using forward history, going to {self.current_index}")
            return True
        
        # Add current to history (except track repeat)
        if self.repeat_mode != RepeatMode.TRACK:
            self.playback_history.append(self.current_index)
        
        # Handle track repeat
        if self.repeat_mode == RepeatMode.TRACK:
            return True  # Stay on same track
        
        # Handle queue repeat
        if self.repeat_mode == RepeatMode.QUEUE:
            self.current_index = (self.current_index + 1) % len(self.songs)
            debug_log(f"next_track(): Queue repeat, moved to {self.current_index}")
            return True
        
        # Handle shuffle
        if self.is_shuffle_effective():
            next_idx = self._get_next_shuffle_song()
            
            # Remove used song from forward queue
            if self.forward_queue and next_idx == self.forward_queue[0]:
                self.forward_queue.pop(0)
            
            self.current_index = next_idx
            debug_log(f"next_track(): Shuffle, moved to {self.current_index}, "
                     f"forward_queue remaining: {len(self.forward_queue)}")
            return True
        
        # Normal progression
        self.current_index += 1
        
        # Check if we reached the end
        if self.current_index >= len(self.songs):
            debug_log(f"next_track(): Reached end of queue")
            return False
        
        debug_log(f"next_track(): Normal progression to {self.current_index}")
        return True
    
    def next_track_skip_missing(self):
        """
        Move to next track, skipping unavailable songs. For auto-progression after song ends.
        Returns True if there's a next available track, False if queue ended.
        """
        if not self.has_songs():
            return False
        
        # Special case: If current song is missing and in track repeat, skip to next
        if self.repeat_mode == RepeatMode.TRACK:
            current_song = self.current_song()
            if current_song and current_song.get('file_missing', False):
                # Force next even in track repeat
                self.repeat_mode = RepeatMode.OFF
                result = self.next_track()
                self.repeat_mode = RepeatMode.TRACK
                return result
            return True  # Stay on current track
        
        # Try to find next available song
        max_attempts = len(self.songs)
        attempts = 0
        
        while attempts < max_attempts:
            if not self.next_track():
                return False
            
            song = self.current_song()
            if song:
                file_path = song.get('url', song.get('filepath', ''))
                if file_path.startswith('file://'):
                    file_path = file_path[7:]
                if os.path.exists(file_path):
                    debug_log(f"next_track_skip_missing(): Found available song at {self.current_index}")
                    return True
            attempts += 1
        
        debug_log(f"next_track_skip_missing(): No more available files in queue")
        return False
    
    def previous_track(self):
        """
        Move to previous track using global playback history.
        When going back, adds current song to forward history for next button.
        Returns True if moved successfully, False if at beginning.
        """
        if not self.has_songs():
            return False
        
        if self.repeat_mode == RepeatMode.TRACK:
            debug_log(f"previous_track(): In track repeat, staying at {self.current_index}")
            return False
        
        if self.playback_history:
            # Save current for forward history
            self.forward_history.append(self.current_index)
            self.current_index = self.playback_history.pop()
            debug_log(f"previous_track(): Moved to {self.current_index}, "
                     f"forward_history: {len(self.forward_history)} items")
            return True
        
        debug_log(f"previous_track(): No history available")
        return False
    
    def set_current_index(self, index):
        """
        Set current playback index. Manual song selection clears forward queue to resync predictions.
        History tracking ensures proper previous button functionality.
        """
        if 0 <= index < len(self.songs):
            # Save current to history
            if self.current_index != index:
                self.playback_history.append(self.current_index)
            
            self.current_index = index
            
            # Clear forward queue and forward history on manual selection
            self.forward_queue.clear()
            self.forward_history.clear()
            
            debug_log(f"set_current_index(): Set to {index}, cleared forward queue/history")
            return True
        return False
    
    def add_song(self, song):
        """Add a song to the queue."""
        self.songs.append(song)
        debug_log(f"add_song(): Added '{song.get('title', 'Unknown')}', total: {len(self.songs)}")
    
    def add_songs(self, songs):
        """Add multiple songs to the queue."""
        self.songs.extend(songs)
        self.playback_history.clear()
        debug_log(f"add_songs(): Added {len(songs)} songs, cleared history")
        print(f"Added {len(songs)} songs to queue")
    
    def remove_song(self, index):
        """Remove a song from the queue."""
        if 0 <= index < len(self.songs):
            removed = self.songs.pop(index)
            if self.current_index >= index:
                self.current_index = max(0, self.current_index - 1)
            debug_log(f"remove_song(): Removed song at {index}, current now: {self.current_index}")
            return True
        return False
    
    def shuffle_queue(self):
        """
        Shuffle the entire queue by randomly reordering all songs.
        This physically reorders the songs list and resets the current index.
        """
        if not self.songs:
            return False
        
        # Get current song before shuffle
        current_song = self.current_song()
        
        # Shuffle the songs list
        random.shuffle(self.songs)
        
        # Find new index of current song
        if current_song:
            for i, song in enumerate(self.songs):
                if song == current_song:
                    self.current_index = i
                    break
        else:
            self.current_index = 0
        
        debug_log(f"shuffle_queue(): Physically shuffled queue, current now at {self.current_index}")
        print("Queue shuffled - song order randomized")
        return True
    
    def play_random_song(self):
        """
        Jump to a completely random song in the queue.
        This doesn't reorder the queue, just changes the current playing position.
        """
        if not self.songs:
            return False
        
        # Select random index
        random_index = random.randint(0, len(self.songs) - 1)
        
        # Save current to history
        self.playback_history.append(self.current_index)
        self.current_index = random_index
        
        # Clear forward queue on manual jump
        self.forward_queue.clear()
        
        song = self.current_song()
        song_title = song.get('title', 'Unknown') if song else 'Unknown'
        debug_log(f"play_random_song(): Jumped to {random_index}")
        print(f"Jumped to random song: {song_title} (position {random_index + 1}/{len(self.songs)})")
        return True
    
    def clear_queue(self):
        """Clear the entire queue and reset all state."""
        self.songs.clear()
        self.current_index = 0
        self.playback_history.clear()
        self.forward_history.clear()
        self.forward_queue.clear()
        debug_log(f"clear_queue(): Queue cleared")
        print("Queue cleared")
    
    def handle_song_finished(self):
        """
        Handle when current song finishes playing. Auto-skips missing files during progression.
        Returns tuple: (should_continue: bool, next_song: dict or None)
        """
        current_song = self.current_song()
        if current_song:
            debug_log(f"handle_song_finished(): Finished '{current_song.get('title', 'Unknown')}'")
        
        # Use next_track_skip_missing to skip missing files during auto-progression
        if self.next_track_skip_missing():
            next_song = self.current_song()
            if next_song:
                debug_log(f"handle_song_finished(): Next song is '{next_song.get('title', 'Unknown')}'")
                return (True, next_song)
        
        debug_log(f"handle_song_finished(): No more songs to play")
        print("Queue finished - no more songs to play")
        return (False, None)

def format_song_info(song):
    """
    Format song information for display with comprehensive metadata.
    
    Args:
        song: Dictionary containing song metadata.
        
    Returns:
        Formatted string with song information.
    """
    artist = song.get('artist') or "Unknown Artist"
    albumartist = song.get('albumartist') or artist
    title = song.get('title') or "Unknown Title"
    album = song.get('album') or "Unknown Album"
    
    # Format duration
    duration = ""
    length = song.get('length', 0)
    if length:
        minutes, seconds = divmod(length, 60)
        duration = f" [{minutes}:{seconds:02d}]"
    
    # Format track number
    track = song.get('track', 0)
    track_str = f"{track:02d}. " if track else ""
    
    # Format year
    year = song.get('year', 0)
    year_str = f" ({year})" if year else ""
    
    return f"{track_str}{artist} - {title} ({albumartist} - {album}{year_str}){duration}"

def display_queue(queue, current_index=0):
    """
    Display the current queue with highlighting for current song.
    
    Args:
        queue: List of song dictionaries to display.
        current_index: Index of currently playing song (default: 0).
    """
    if not queue:
        print("Queue is empty.")
        return
    
    print(f"\n=== Audio Queue ({len(queue)} songs) ===")
    for i, song in enumerate(queue):
        marker = "> " if i == current_index else "  "
        print(f"{marker}{i+1:3d}. {format_song_info(song)}")
    print()

def play_queue_with_manager(songs, repeat_mode="off", shuffle=False, start_index=0):
    """
    Play songs using QueueManager with AudioPlayer - non-blocking with command interface.
    
    Args:
        songs: List of song dictionaries from playlists
        repeat_mode: Repeat mode - "off", "track", or "queue"
        shuffle: Enable shuffle mode
        start_index: Index to start playback from
    """
    if not songs:
        print("Queue is empty. Nothing to play.")
        return
    
    # Create queue manager
    queue_manager = QueueManager(songs)
    queue_manager.set_repeat_mode(repeat_mode)
    queue_manager.set_shuffle_mode(shuffle)
    queue_manager.current_index = start_index
    
    # Create audio player instance
    player = AudioPlayer(debug=False)
    
    # Playback control flags
    playback_active = {'running': True, 'skip_requested': False, 'previous_requested': False}
    playback_lock = threading.Lock()
    
    def playback_thread():
        """Background thread that handles actual playback."""
        try:
            while playback_active['running'] and queue_manager.has_songs():
                song = queue_manager.current_song()
                if not song:
                    break
                
                # Get file path
                file_path = song.get('url', song.get('filepath', ''))
                if file_path.startswith('file://'):
                    file_path = file_path[7:]
                
                # Check if file exists
                if not os.path.exists(file_path):
                    print(f"\nFile not found: {file_path}")
                    song['file_missing'] = True
                    
                    if not queue_manager.next_track_skip_missing():
                        break
                    continue
                
                # Display song info
                print(f"\n[{queue_manager.current_index + 1}/{len(songs)}] Now playing: {format_song_info(song)}")
                print(f"File: {file_path}")
                
                # Load and play the song
                if not player.load_file(file_path):
                    if not queue_manager.next_track_skip_missing():
                        break
                    continue
                
                if not player.play():
                    if not queue_manager.next_track_skip_missing():
                        break
                    continue
                
                # Show prompt after playback starts
                print("queue/play> ", end="", flush=True)
                
                # Track if we manually changed tracks
                manual_track_change = False
                
                # Wait for playback to complete or command
                while player.is_playing and playback_active['running']:
                    with playback_lock:
                        if playback_active['skip_requested']:
                            playback_active['skip_requested'] = False
                            manual_track_change = True
                            player.stop()
                            if not queue_manager.next_track_skip_missing():
                                playback_active['running'] = False
                            break
                        if playback_active['previous_requested']:
                            playback_active['previous_requested'] = False
                            manual_track_change = True
                            player.stop()
                            # previous_track() returns False if can't go back
                            if not queue_manager.previous_track():
                                print("Already at beginning of playback history.")
                                manual_track_change = False  # Stay on current song
                            break
                    time.sleep(0.1)
                
                # Check if we should quit
                if not playback_active['running']:
                    player.stop()
                    break
                
                # Move to next track after natural playback completion (not manual skip/previous)
                if not manual_track_change:
                    if not queue_manager.next_track_skip_missing():
                        break
        
        finally:
            player.stop()
            playback_active['running'] = False
    
    # Start playback thread
    thread = threading.Thread(target=playback_thread, daemon=True)
    thread.start()
    
    # Print initial status
    print(f"\n=== Playing {len(songs)} songs ===")
    print(f"Repeat mode: {repeat_mode}")
    print(f"Shuffle: {'ON' if shuffle else 'OFF'}")
    print(f"Volume: {player.get_volume():.2f}")
    print("\nPlayback running in background. Type commands below:")
    print("Commands: next, previous, pause, resume, stop, current, queue, list, volume, seek, shuffle, repeat, backlog, help")
    
    # Command loop
    while playback_active['running'] and thread.is_alive():
        try:
            command = input("queue/play> ").strip().lower()
            
            if not command:
                continue
            
            if command in ['quit', 'q', 'stop']:
                playback_active['running'] = False
                player.should_quit = True
                print("Stopping playback...")
                break
            
            elif command in ['next', 'n', 'skip']:
                with playback_lock:
                    playback_active['skip_requested'] = True
                    if not queue_manager.next_track_skip_missing():
                        print("Reached end of queue.")
                        playback_active['running'] = False
                    else:
                        print("Skipping to next track...")
            
            elif command in ['previous', 'prev', 'p']:
                with playback_lock:
                    playback_active['previous_requested'] = True
            
            elif command == 'pause':
                player.pause()
            
            elif command == 'resume':
                player.play()
            
            elif command in ['current', 'c', 'now']:
                current = queue_manager.current_song()
                if current:
                    print("\n=== Current Song ===")
                    print(f"Position: [{queue_manager.current_index + 1}/{len(queue_manager.songs)}]")
                    print(f"Title: {current.get('title', 'Unknown')}")
                    print(f"Artist: {current.get('artist', 'Unknown')}")
                    print(f"Album: {current.get('album', 'Unknown')}")
                    print(f"Duration: {current.get('length', 0)} seconds")
                    
                    # Show playback position
                    position = player.get_position()
                    duration = player.duration
                    if position >= 0 and duration > 0:
                        progress = (position / duration) * 100
                        print(f"Playback: {position:.1f}s / {duration:.1f}s ({progress:.1f}%)")
                    print()
                else:
                    print("No song currently playing.")
            
            elif command.startswith('volume') or command.startswith('vol') or command == 'v':
                parts = command.split()
                if len(parts) > 1:
                    try:
                        vol_input = parts[1]
                        if vol_input.startswith('+'):
                            adjustment = float(vol_input[1:]) if len(vol_input) > 1 else 0.1
                            new_vol = min(1.0, player.get_volume() + adjustment)
                            player.set_volume(new_vol)
                        elif vol_input.startswith('-'):
                            adjustment = float(vol_input[1:]) if len(vol_input) > 1 else 0.1
                            new_vol = max(0.0, player.get_volume() - adjustment)
                            player.set_volume(new_vol)
                        else:
                            new_vol = float(vol_input)
                            player.set_volume(new_vol)
                    except ValueError:
                        print("Invalid volume value. Usage: volume <0.0-1.0>, volume +0.1, volume -0.1")
                else:
                    print(f"Current volume: {player.get_volume():.2f}")
            
            elif command.startswith('seek') or command == 'k':
                parts = command.split()
                if len(parts) > 1:
                    try:
                        seek_input = parts[1]
                        if seek_input.startswith('+'):
                            adjustment = float(seek_input[1:])
                            current_pos = player.get_position()
                            if current_pos >= 0:
                                player.seek(current_pos + adjustment)
                        elif seek_input.startswith('-'):
                            adjustment = float(seek_input[1:])
                            current_pos = player.get_position()
                            if current_pos >= 0:
                                player.seek(max(0, current_pos - adjustment))
                        else:
                            position = float(seek_input)
                            player.seek(position)
                    except ValueError:
                        print("Invalid seek position. Usage: seek <seconds>, seek +10, seek -10")
                else:
                    position = player.get_position()
                    duration = player.duration
                    if position >= 0:
                        print(f"Current position: {position:.1f}s / {duration:.1f}s")
            
            elif command in ['shuffle', 's']:
                new_shuffle = not queue_manager.shuffle
                queue_manager.set_shuffle_mode(new_shuffle)
            
            elif command in ['repeat', 'r']:
                modes = [RepeatMode.OFF, RepeatMode.TRACK, RepeatMode.QUEUE]
                current_idx = modes.index(queue_manager.repeat_mode)
                next_mode = modes[(current_idx + 1) % len(modes)]
                queue_manager.set_repeat_mode(next_mode)
            
            elif command in ['backlog', 'history', 'b']:
                if queue_manager.playback_history:
                    print("\n=== Playback History (Backlog) ===")
                    recent_history = queue_manager.playback_history[-20:]
                    for i, idx in enumerate(recent_history, 1):
                        if 0 <= idx < len(queue_manager.songs):
                            song = queue_manager.songs[idx]
                            print(f"  {i:2d}. {format_song_info(song)}")
                    if len(queue_manager.playback_history) > 20:
                        print(f"\n  ... and {len(queue_manager.playback_history) - 20} more songs in history")
                    print()
                else:
                    print("No playback history yet.")
            
            elif command in ['queue', 'show', 'q']:
                # Show upcoming songs in queue
                current_idx = queue_manager.current_index
                print("\n=== Upcoming Queue ===")
                print(f"Currently playing: [{current_idx + 1}/{len(queue_manager.songs)}]")
                
                # Show next 10 songs
                upcoming_count = 0
                temp_idx = current_idx
                shown_indices = set()
                
                # Simulate what would play next based on current queue manager state
                for i in range(min(10, len(queue_manager.songs))):
                    # Calculate next index based on repeat mode
                    if queue_manager.repeat_mode == RepeatMode.TRACK:
                        next_idx = temp_idx
                    elif queue_manager.repeat_mode == RepeatMode.QUEUE:
                        next_idx = (temp_idx + 1) % len(queue_manager.songs)
                    else:
                        next_idx = temp_idx + 1
                        if next_idx >= len(queue_manager.songs):
                            break
                    
                    if next_idx < len(queue_manager.songs):
                        song = queue_manager.songs[next_idx]
                        marker = "(repeat)" if next_idx in shown_indices else ""
                        print(f"  {i+1:2d}. {format_song_info(song)} {marker}")
                        shown_indices.add(next_idx)
                        temp_idx = next_idx
                    else:
                        break
                
                remaining = len(queue_manager.songs) - current_idx - 1
                if remaining > 10:
                    print(f"\n  ... and {remaining - 10} more songs")
                print()
            
            elif command in ['list']:
                # Show entire queue
                print("\n=== Complete Queue ===")
                current_idx = queue_manager.current_index
                for i, song in enumerate(queue_manager.songs):
                    marker = ">" if i == current_idx else " "
                    print(f"{marker}  {i+1:3d}. {format_song_info(song)}")
                print(f"\nTotal: {len(queue_manager.songs)} songs")
                print(f"Shuffle: {'ON' if queue_manager.shuffle else 'OFF'}")
                print(f"Repeat: {queue_manager.repeat_mode.name}\n")
            
            elif command == 'help':
                print("\nPlayback Commands:")
                print("  next/n - Skip to next track")
                print("  previous/p - Go to previous track")
                print("  pause - Pause playback")
                print("  resume - Resume playback")
                print("  stop/quit - Stop playback and return to queue mode")
                print("  current/c - Show current song info and position")
                print("  queue/show - Show upcoming songs in queue")
                print("  list - Show entire queue with current position")
                print("  volume <0.0-1.0> - Set volume (or volume +0.1, volume -0.1)")
                print("  seek <seconds> - Seek to position (or seek +10, seek -10)")
                print("  shuffle - Toggle shuffle mode")
                print("  repeat - Cycle repeat modes (off → track → queue)")
                print("  backlog - View playback history")
                print()
            
            else:
                print(f"Unknown command: {command}. Type 'help' for available commands.")
        
        except KeyboardInterrupt:
            print("\nStopping playback...")
            playback_active['running'] = False
            player.should_quit = True
            break
        except EOFError:
            print("\nStopping playback...")
            playback_active['running'] = False
            player.should_quit = True
            break
        except Exception as e:
            print(f"Error: {e}")
    
    # Wait for playback thread to finish
    thread.join(timeout=2.0)
    print("\nPlayback finished.")

def play_queue(queue, shuffle=False, repeat=False, repeat_track=False, start_index=0):
    """
    Play songs in the queue with various playback options.
    
    Args:
        queue: List of song dictionaries to play.
        shuffle: Enable shuffle mode (default: False).
        repeat: Enable queue repeat (default: False).
        repeat_track: Enable track repeat (default: False).
        start_index: Index to start playback from (default: 0).
    """
    # Determine repeat mode
    if repeat_track:
        repeat_mode = "track"
    elif repeat:
        repeat_mode = "queue"
    else:
        repeat_mode = "off"
    
    play_queue_with_manager(queue, repeat_mode, shuffle, start_index)

def interactive_mode():
    """
    Interactive mode for queue management.
    
    Provides a command-line interface for managing audio queues with
    commands for loading and playing songs from playlists.
    
    Note: For database-powered queue management, use db_queue.py instead.
    """
    queue = []
    
    print("\n=== Interactive Audio Queue Mode ===")
    print("Commands:")
    print("  playlist - Load songs from M3U playlist file")
    print("  show - Show current queue")
    print("  play - Play current queue")
    print("  shuffle - Toggle shuffle mode")
    print("  repeat - Toggle repeat mode")
    print("  clear - Clear current queue")
    print("  info - Show playback controls information")
    print("  quit - Exit interactive mode")
    print()
    print("Note: During playback, type commands directly (no need to pause).")
    print()
    print("For database queries, filtering, and search, use db_queue.py instead.")
    print()
    
    shuffle_mode = False
    repeat_mode = False
    
    while True:
        try:
            command = input("queue> ").strip().lower()
            
            if command in ['quit', 'q', 'exit']:
                break
            elif command == 'show':
                display_queue(queue)
            elif command == 'play':
                if queue:
                    play_queue(queue, shuffle_mode, repeat_mode, False, 0)
                else:
                    print("Queue is empty. Use 'playlist' to add songs first.")
            elif command == 'shuffle':
                shuffle_mode = not shuffle_mode
                print(f"Shuffle mode: {'ON' if shuffle_mode else 'OFF'}")
            elif command == 'repeat':
                repeat_mode = not repeat_mode
                print(f"Repeat mode: {'ON' if repeat_mode else 'OFF'}")
            elif command == 'playlist':
                playlist_path = input("Enter playlist file path: ").strip()
                if not os.path.exists(playlist_path):
                    print(f"Error: Playlist file '{playlist_path}' not found.")
                    continue
                
                songs = load_m3u_playlist(playlist_path)
                if songs:
                    queue = list(songs)
                    print(f"Loaded {len(queue)} songs from playlist '{playlist_path}'.")
                else:
                    print("No songs found in playlist or failed to load.")
            elif command == 'clear':
                queue = []
                print("Queue cleared.")
            elif command == 'info':
                print("\n=== Playback Controls (available during playback) ===")
                print("While music is playing, type commands directly:")
                print("  next/n - Skip to next track")
                print("  previous/p - Go to previous track")
                print("  pause - Pause playback")
                print("  resume - Resume playback")
                print("  stop/quit - Stop playback and return to queue mode")
                print("  current/c - Show current song info and playback position")
                print("  queue/show - Show upcoming songs in queue")
                print("  list - Show entire queue with current position")
                print("  volume <value> - Set volume (0.0-1.0), or volume +0.1, volume -0.1")
                print("  seek <seconds> - Seek to position, or seek +10, seek -10")
                print("  shuffle - Toggle shuffle mode on/off")
                print("  repeat - Cycle through repeat modes (off → track → queue)")
                print("  backlog - View playback history (last 20 songs)")
                print("  help - Show these commands\n")
                print("Note: Commands work in real-time while music plays. No need to pause!\n")
            elif command == 'help':
                print("Commands: list, filter, load, playlist, show, play, shuffle, repeat, clear, info, quit")
            else:
                print("Unknown command. Type 'help' for available commands.")
                
        except KeyboardInterrupt:
            print("\nExiting interactive mode...")
            break
        except Exception as e:
            print(f"Error: {e}")

def main():
    """
    Main function for audio queue management command-line interface.
    
    Provides a command-line interface for managing audio queues from
    M3U playlist files with shuffle and repeat modes.
    
    For database-powered queue management, use db_queue.py instead.
    """
    parser = argparse.ArgumentParser(
        description='Audio Queue Manager - Manage and play audio queues from playlists',
        epilog='Examples:\n'
               '  python queue.py --playlist myplaylist.m3u --repeat\n'
               '  python queue.py --playlist myplaylist.m3u --shuffle --repeat-track\n'
               '  python queue.py --interactive',
        formatter_class=argparse.RawDescriptionHelpFormatter
    )
    
    # Playlist loading
    parser.add_argument('--playlist', help='Load M3U playlist file')
    
    # Playback options
    parser.add_argument('--shuffle', action='store_true', help='Enable shuffle mode')
    parser.add_argument('--repeat', action='store_true', help='Enable queue repeat')
    parser.add_argument('--repeat-track', action='store_true', help='Enable track repeat')
    parser.add_argument('--start', type=int, default=0, help='Start index (0-based)')
    
    # Interactive mode
    parser.add_argument('--interactive', action='store_true', help='Enter interactive mode')
    
    args = parser.parse_args()
    
    # Load songs
    songs = []
    
    if args.playlist:
        # Load from playlist
        songs = load_m3u_playlist(args.playlist)
        if not songs:
            print(f"Failed to load playlist: {args.playlist}")
            return 1
        print(f"Loaded {len(songs)} songs from playlist")
    elif args.interactive:
        # Interactive mode - load playlists interactively
        interactive_mode()
        return 0
    else:
        # Non-interactive mode requires a playlist
        print("Error: No playlist specified. Use --playlist or --interactive mode.")
        print("For database queries, use db_queue.py instead.")
        return 1
    
    # Start playback
    play_queue(songs, args.shuffle, args.repeat, args.repeat_track, args.start)
    
    return 0

if __name__ == '__main__':
    sys.exit(main())
