# modules/sorted_renderer.py

import xbmcplugin
import xbmcgui
import urllib.parse

from .index_loader import load_index

def render(handle, addon_id, mode):
    data = load_index()

    entries = data.get(mode)
    if not entries:
        xbmcgui.Dialog().ok("RD Tools", f"No entries for {mode}")
        return

    xbmcplugin.setContent(handle, "files")

    for entry in entries:
        label = entry.get("label", "Unknown")
        file_url = entry.get("file", "")

        url = (
            f"plugin://{addon_id}/?action=sorted_list"
            f"&group={mode}"
            f"&label={urllib.parse.quote(label)}"
            f"&file_url={urllib.parse.quote(file_url)}"
        )

        li = xbmcgui.ListItem(label)
        xbmcplugin.addDirectoryItem(handle, url, li, True)

    xbmcplugin.endOfDirectory(handle)
