import os
import pickle

QUEUE_LOCATION = "/var/lib/sam/queue"
LEGACY_QUEUE_LOCATION = "/var/run/sam_queue"

# Priority order for displaying current queue item: System first, then Flatpak, then SWAI
MANAGER_PRIORITY = ["system", "flathub", "fedora", "swai"]


def get_queue_file_for_manager(manager_id: str) -> str:
    """Get the queue file path for a specific manager."""
    return f"{QUEUE_LOCATION}_{manager_id}"


def get_legacy_queue_file_for_manager(manager_id: str) -> str:
    """Get the old runtime queue file path for migration."""
    return f"{LEGACY_QUEUE_LOCATION}_{manager_id}"


def _read_queue_file(filepath: str):
    """Read a queue file and return its contents."""
    try:
        with open(filepath, "rb") as file:
            return pickle.load(file)
    except FileNotFoundError:
        return None
    except EOFError:
        return None
    except Exception as e:
        print(e)
        return None


def _get_manager_queues_from_location(queue_location: str) -> dict:
    """Get manager queues from queue files sharing a base path."""
    queues = {}
    queue_dir = os.path.dirname(queue_location) or "/var/run"
    queue_prefix = os.path.basename(queue_location) + "_"
    
    try:
        for filename in os.listdir(queue_dir):
            if filename.startswith(queue_prefix):
                manager_id = filename[len(queue_prefix):]
                filepath = os.path.join(queue_dir, filename)
                queue_data = _read_queue_file(filepath)
                if queue_data:
                    queues[manager_id] = queue_data
    except Exception as e:
        print(e)
    
    return queues


def _get_all_manager_queues() -> dict:
    """Get all manager queues from disk."""
    queues = _get_manager_queues_from_location(QUEUE_LOCATION)
    for manager_id, actions in _get_manager_queues_from_location(LEGACY_QUEUE_LOCATION).items():
        if os.path.exists(get_queue_file_for_manager(manager_id)):
            continue
        queues.setdefault(manager_id, actions)
    return queues


def get_manager_queue_dicts() -> dict:
    """Get persisted queues keyed by manager ID."""
    return _get_all_manager_queues()


def get_queue_dicts():
    """Get all queue items from all managers as a flat list."""
    queues = _get_all_manager_queues()
    all_actions = []
    for manager_id, actions in queues.items():
        if actions:
            all_actions.extend(actions)
    return all_actions if all_actions else None


def get_current_queue_item():
    """Get the current queue item, prioritizing by manager type.
    
    Priority: System > Flatpak remotes > SWAI
    """
    queues = _get_all_manager_queues()
    
    if not queues:
        return None
    
    # Check managers in priority order
    for priority_manager in MANAGER_PRIORITY:
        if priority_manager in queues and queues[priority_manager]:
            return queues[priority_manager][0]
    
    # Fall back to any manager with items (for unknown managers like other flatpak remotes)
    for manager_id, actions in queues.items():
        if actions:
            return actions[0]
    
    return None
