# -*- coding: utf-8 -*-
"""CloudDrive2 Plugin Utility Functions"""

import os
import sys
import time
import json
import logging

from .cd2_constants import ADDON_ID

# Kodi modules - only available inside Kodi runtime
try:
    import xbmc
    import xbmcaddon
    import xbmcvfs
    _IN_KODI = True
except ImportError:
    _IN_KODI = False


def _get_data_dir():
    """Get data directory for token storage. Works in and out of Kodi."""
    if _IN_KODI:
        addon = xbmcaddon.Addon(ADDON_ID)
        return xbmcvfs.translatePath(addon.getAddonInfo("profile"))
    else:
        return os.path.expanduser("~/.config/clouddrive2-plugin")


def profile_path():
    return _get_data_dir()


def ensure_profile_dir():
    path = profile_path()
    if not os.path.exists(path):
        os.makedirs(path)


def get_token_path():
    ensure_profile_dir()
    return os.path.join(profile_path(), "token.json")


def save_token(token):
    with open(get_token_path(), "w") as f:
        json.dump({"token": token, "saved_at": time.time()}, f)


def load_token():
    path = get_token_path()
    if os.path.exists(path):
        with open(path, "r") as f:
            data = json.load(f)
            return data.get("token")
    return None


def clear_token():
    path = get_token_path()
    if os.path.exists(path):
        os.remove(path)


def log(msg, level=None):
    """Log message to Kodi or stdout depending on runtime."""
    if _IN_KODI:
        if level is None:
            level = xbmc.LOGINFO
        xbmc.log(f"[CloudDrive2] {msg}", level)
    else:
        print(f"[CloudDrive2] {msg}")


def format_size(size_bytes):
    """Convert bytes to human-readable size string."""
    if size_bytes is None:
        return ""
    try:
        size_bytes = int(size_bytes)
    except (ValueError, TypeError):
        return str(size_bytes)
    if size_bytes <= 0:
        return ""
    if size_bytes >= 1024 * 1024 * 1024:
        return f"{size_bytes / (1024 * 1024 * 1024):.2f} GB"
    if size_bytes >= 1024 * 1024:
        return f"{size_bytes / (1024 * 1024):.1f} MB"
    if size_bytes >= 1024:
        return f"{size_bytes / 1024:.1f} KB"
    return f"{size_bytes} B"


def format_time(ts):
    """Format a timestamp to readable string."""
    if ts is None:
        return ""
    try:
        secs = int(ts)
        tm = time.localtime(secs)
        return time.strftime("%Y-%m-%d %H:%M", tm)
    except Exception:
        return str(ts)


def is_service_running(host="localhost", port=19798, timeout=3):
    """Check if CloudDrive2 gRPC service is reachable."""
    import socket
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(timeout)
        result = sock.connect_ex((host, port))
        sock.close()
        return result == 0
    except Exception:
        return False


def wait_for_service(timeout=15):
    """Wait for CloudDrive2 service to become available."""
    interval = 0.5
    waited = 0
    while waited < timeout:
        if is_service_running():
            return True
        time.sleep(interval)
        waited += interval
    return False
