"""Kodi native resume/bookmark integration via JSON-RPC and VideoInfoTag."""
from __future__ import annotations

import json

import xbmc
import xbmcgui

from . import logger

RESUME_THRESHOLD_SECONDS = 30


def get_file_resume(file_path: str) -> tuple[float, float]:
    rpc = getattr(xbmc, "executeJSONRPC", None)
    if not callable(rpc):
        return 0.0, 0.0

    query = json.dumps(
        {
            "jsonrpc": "2.0",
            "method": "Files.GetFileDetails",
            "params": {
                "file": file_path,
                "media": "video",
                "properties": ["resume"],
            },
            "id": 1,
        }
    )
    try:
        response = json.loads(rpc(query))
        resume = response.get("result", {}).get("filedetails", {}).get("resume", {})
        position = float(resume.get("position") or 0)
        total = float(resume.get("total") or 0)
        return position, total
    except (json.JSONDecodeError, TypeError, ValueError) as exc:
        logger.debug(f"Resume lookup failed for {file_path}: {exc}")
        return 0.0, 0.0


def _get_video_info_tag(item: xbmcgui.ListItem):
    getter = getattr(item, "getVideoInfoTag", None)
    if getter is None:
        return None
    if callable(getter):
        try:
            return getter()
        except TypeError:
            return None
    return getter


def _call_if_exists(obj, name: str, *args) -> bool:
    method = getattr(obj, name, None)
    if callable(method):
        method(*args)
        return True
    return False


def _apply_playback_metadata(
    item: xbmcgui.ListItem,
    file_path: str,
    title: str,
    duration_seconds: int,
    plot: str,
    lookup_resume: bool = True,
) -> None:
    position, total = get_file_resume(file_path) if lookup_resume else (0.0, 0.0)
    total = total or float(duration_seconds)

    tag = _get_video_info_tag(item)
    if tag is not None:
        _call_if_exists(tag, "setFile", file_path)
        if title:
            _call_if_exists(tag, "setTitle", title)
        if plot:
            _call_if_exists(tag, "setPlot", plot)
        if duration_seconds > 0:
            _call_if_exists(tag, "setDuration", int(duration_seconds))

    if position >= RESUME_THRESHOLD_SECONDS and total > 0:
        if tag is None or not _call_if_exists(tag, "setResumePoint", position, total):
            item.setProperty("ResumeTime", str(position))
            item.setProperty("TotalTime", str(int(total)))
        logger.debug(f"Kodi resume {position:.0f}/{total:.0f}s for {file_path}")
    elif duration_seconds > 0 and tag is None:
        item.setProperty("TotalTime", str(int(total)))


def apply_playback_metadata(
    item: xbmcgui.ListItem,
    file_path: str,
    title: str,
    duration_seconds: int,
    plot: str = "",
    lookup_resume: bool = True,
) -> None:
    try:
        _apply_playback_metadata(
            item, file_path, title, duration_seconds, plot, lookup_resume=lookup_resume
        )
    except Exception as exc:
        logger.error(f"Resume metadata failed for {file_path}: {exc}")

