# -*- coding: utf-8 -*-
# RD Tools - Shared Utility Functions
# ---------------------------------------------------------------------------
# Core utilities shared by all RD Tools modules.
# Includes: VFS-safe copy, path joiners, file/folder browsers, notifications,
# and universal progress-speed-ETA updater.
# ---------------------------------------------------------------------------

import os
import time
import xbmcgui
import xbmcvfs

CHUNK_SIZE = 1024 * 128  # 128 KB


# =============================================================================
# PATH HELPERS
# =============================================================================

def join_path(folder, name):
    """Safely join two Kodi VFS paths."""
    return folder.rstrip('/') + '/' + name


# =============================================================================
# FILE COPY HELPERS
# =============================================================================

def copy_vfs(src_path, dst_path):
    """
    Copy a single file across Kodi's VFS safely.
    Tries xbmcvfs.copy() first, then manual read/write fallback.
    """
    try:
        if xbmcvfs.copy(src_path, dst_path):
            return True
    except Exception:
        pass

    try:
        src_f = xbmcvfs.File(src_path, 'rb')
        dst_f = xbmcvfs.File(dst_path, 'wb')
        while True:
            chunk = src_f.read(CHUNK_SIZE)
            if not chunk:
                break
            dst_f.write(chunk)
        src_f.close()
        dst_f.close()
        return True
    except Exception:
        return False


def copy_directory(src_folder, dst_folder):
    """Recursively copy all files and subdirectories."""
    if not xbmcvfs.exists(dst_folder):
        xbmcvfs.mkdirs(dst_folder)

    dirs, files = xbmcvfs.listdir(src_folder)
    for f in files:
        copy_vfs(join_path(src_folder, f), join_path(dst_folder, f))
    for d in dirs:
        copy_directory(join_path(src_folder, d), join_path(dst_folder, d))


# =============================================================================
# FILE/FOLDER BROWSERS
# =============================================================================

def browse_file_kodi_root(title):
    return xbmcgui.Dialog().browse(1, title, 'files', '', False, False, 'special://home/')

def browse_folder_kodi_root(title):
    return xbmcgui.Dialog().browse(0, title, 'files', '', False, True, 'special://home/')

def browse_file_device_fs(title):
    return xbmcgui.Dialog().browse(1, title, 'files', '', False, False, '')

def browse_folder_device_fs(title):
    return xbmcgui.Dialog().browse(0, title, 'files', '', False, True, '')


# =============================================================================
# UI HELPERS
# =============================================================================

def notify(title, message, icon=xbmcgui.NOTIFICATION_INFO, duration=3000):
    xbmcgui.Dialog().notification(title, message, icon, duration)


# =============================================================================
# PROGRESS + SPEED + ETA HELPER
# =============================================================================

def progress_speed_eta(dp, index, total, processed_bytes, total_bytes, start_time, current_name, title="Processing"):
    """
    Update a DialogProgressBG with dynamic progress, speed, and ETA.
    """
    elapsed = max(time.time() - start_time, 0.01)
    speed = (processed_bytes / 1024 / 1024) / elapsed
    remaining = max(total_bytes - processed_bytes, 0)
    eta = (remaining / (speed * 1024 * 1024)) if speed > 0 else 0
    eta_str = time.strftime("%M:%S", time.gmtime(eta))
    percent = int((index / total) * 100) if total > 0 else 0

    dp.update(
        percent,
        f"{title} {index}/{total} • {speed:.1f} MB/s",
        f"{current_name} | ETA: {eta_str}"
    )
