"""Build Kodi directory listings."""
from __future__ import annotations

from typing import Any

import xbmcgui
import xbmcplugin

from xbmcaddon import Addon

from .constants import ADDON_ID
from .kodi_resume import apply_playback_metadata
from .utils import upgrade_channel_logo_url


def channel_art(channel: dict[str, Any]) -> dict[str, str] | None:
    logo = upgrade_channel_logo_url(
        (channel.get("logo") or channel.get("icon") or channel.get("image") or "").strip()
    )
    if not logo:
        return None
    return {"thumb": logo, "icon": logo, "poster": logo}


def apply_art(item: xbmcgui.ListItem, art: dict[str, str] | None) -> None:
    if not art:
        return
    item.setArt(art)
    icon = art.get("icon") or art.get("thumb")
    if icon:
        item.setProperty("Icon", icon)


def add_item(
    handle: int,
    label: str,
    url: str,
    is_folder: bool = True,
    art: dict[str, str] | None = None,
    playable: bool = False,
    info: dict[str, Any] | None = None,
    context_menu: list[tuple[str, str]] | None = None,
    duration_seconds: int = 0,
    lookup_resume: bool = False,
) -> None:
    if not url or not url.startswith("plugin://"):
        raise ValueError(f"Invalid plugin URL: {url!r}")

    item = xbmcgui.ListItem(label, "", url, True)
    apply_art(item, art)
    if playable:
        item.setProperty("IsPlayable", "true")
        plot = info.get("plot", "") if info else ""
        apply_playback_metadata(
            item, url, label, duration_seconds, plot=plot, lookup_resume=lookup_resume
        )
    if context_menu:
        item.addContextMenuItems(context_menu)
    xbmcplugin.addDirectoryItem(handle, url, item, isFolder=is_folder)


def begin_directory(handle: int) -> None:
    xbmcplugin.setContent(handle, "videos")
    xbmcplugin.addSortMethod(handle, xbmcplugin.SORT_METHOD_PLAYLIST_ORDER)
    xbmcplugin.addSortMethod(handle, xbmcplugin.SORT_METHOD_UNSORTED, "%U")


def end_directory(handle: int) -> None:
    addon = Addon(ADDON_ID)
    xbmcplugin.setPluginCategory(handle, addon.getLocalizedString(30010))
    xbmcplugin.endOfDirectory(handle)


def item_icon(item: dict[str, Any]) -> dict[str, str] | None:
    icon = upgrade_channel_logo_url((item.get("icon") or item.get("image") or "").strip())
    return {"thumb": icon, "icon": icon, "poster": icon} if icon else None
