# -*- coding: utf-8 -*-
"""
CloudDrive2 Kodi Service - Background service that monitors the CD2 daemon.
Automatically starts on Kodi startup.
"""

import os
import stat
import subprocess
import sys

import xbmc
import xbmcgui

from resources.lib import cd2_utils

log = cd2_utils.log

MONITOR_INTERVAL = 30  # seconds between checks

_ADDON_DIR = os.path.dirname(os.path.abspath(__file__))
_PROXY_PATH = os.path.join(_ADDON_DIR, "resources", "lib", "cd2_grpc_proxy.py")
_PROXY_PORT = 19799
_CD2_BIN = os.path.join(_ADDON_DIR, "clouddrive")


def _ensure_executable():
    """Ensure the clouddrive binary has 755 permissions."""
    if os.path.exists(_CD2_BIN):
        current = os.stat(_CD2_BIN).st_mode
        target = stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH
        if (current & 0o777) != 0o755:
            try:
                os.chmod(_CD2_BIN, target)
                log("Fixed clouddrive permissions to 755")
            except Exception as e:
                log(f"Failed to chmod clouddrive: {e}", xbmc.LOGERROR)


def _proxy_running():
    """Check if the gRPC proxy is already running."""
    import socket
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(1)
        result = sock.connect_ex(("localhost", _PROXY_PORT))
        sock.close()
        return result == 0
    except Exception:
        return False


def _start_proxy():
    """Start the gRPC proxy if not already running."""
    if _proxy_running():
        log("gRPC proxy already running")
        return
    log("Starting gRPC proxy...")
    try:
        subprocess.Popen(
            [sys.executable, _PROXY_PATH],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
        )
        log("gRPC proxy started")
    except Exception as e:
        log(f"Failed to start gRPC proxy: {e}", xbmc.LOGERROR)


class CloudDrive2Monitor(xbmc.Monitor):
    """Monitor class that periodically checks CD2 service health."""

    def __init__(self):
        super().__init__()
        self._service_was_down = False

    def check(self):
        running = cd2_utils.is_service_running()
        if running and self._service_was_down:
            log("CloudDrive2 service restored!")
            xbmcgui.Dialog().notification(
                "CloudDrive2", "Service is now running!", time=5000
            )
            self._service_was_down = False
        elif not running and not self._service_was_down:
            log("CloudDrive2 service is not running", xbmc.LOGWARNING)
            self._service_was_down = True

    def run(self):
        log("CloudDrive2 monitor started")
        _ensure_executable()
        _start_proxy()
        while not self.abortRequested():
            self.check()
            if self.waitForAbort(MONITOR_INTERVAL):
                break
        log("CloudDrive2 monitor stopped")


if __name__ == "__main__":
    monitor = CloudDrive2Monitor()
    monitor.run()
