# -*- coding: utf-8 -*-
"""Mount Point Management - mount/unmount cloud drives to local filesystem."""

import sys
import os
import urllib.parse

import xbmcplugin
import xbmcgui
import xbmc

from .cd2_client import get_client
from .cd2_constants import MODE_MOUNT_ADD, MODE_MOUNT_RESTORE, MODE_NOOP
from .cd2_l10n import _, __
from . import cd2_utils

log = cd2_utils.log


def show_mount_list(handle):
    """Display all mount points and their status."""
    client = get_client()
    xbmcplugin.setContent(handle, "files")

    # Restore default config button
    url = _build_url(MODE_MOUNT_RESTORE)
    li = xbmcgui.ListItem(f"[B]{_(32180)}[/B]")
    li.setProperty("IsPlayable", "false")
    xbmcplugin.addDirectoryItem(handle, url, li, isFolder=False)

    try:
        resp = client.get_mount_points(timeout=5)
    except Exception as e:
        log(f"Failed to get mount points: {e}")
        xbmcgui.Dialog().ok(_(32030), _(32035, str(e)))
        xbmcplugin.endOfDirectory(handle)
        return

    mount_points = []
    if hasattr(resp, 'mountPoints') and resp.mountPoints:
        mount_points = resp.mountPoints

    # Also get cloud APIs for reference
    cloud_apis = {}
    try:
        api_resp = client.get_all_cloud_apis(timeout=5)
        if hasattr(api_resp, 'apis') and api_resp.apis:
            for api in api_resp.apis:
                name = api.name if hasattr(api, 'name') else ""
                if name:
                    cloud_apis[name] = api
    except Exception:
        pass

    if mount_points:
        for mp in mount_points:
            mount_point = mp.mountPoint if hasattr(mp, 'mountPoint') else ""
            source_dir = mp.sourceDir if hasattr(mp, 'sourceDir') else ""
            is_mounted = mp.isMounted if hasattr(mp, 'isMounted') else False

            status = f"[COLOR green]{_(32070)}[/COLOR]" if is_mounted else f"[COLOR red]{_(32071)}[/COLOR]"
            label = f"{status}  {mount_point}  ({source_dir})"

            li = xbmcgui.ListItem(label)
            li.setProperty("IsPlayable", "false")

            noop_url = _build_url(MODE_NOOP)
            xbmcplugin.addDirectoryItem(handle, noop_url, li, isFolder=False)
    else:
        li = xbmcgui.ListItem(f"[{_(32074)}]")
        li.setProperty("IsPlayable", "false")
        noop_url = _build_url(MODE_NOOP)
        xbmcplugin.addDirectoryItem(handle, noop_url, li, isFolder=False)

    xbmcplugin.endOfDirectory(handle)


def show_add_mount_menu(handle):
    """Show available cloud APIs that can be mounted."""
    client = get_client()
    xbmcplugin.setContent(handle, "files")

    # Restore default config button
    url = _build_url(MODE_MOUNT_RESTORE)
    li = xbmcgui.ListItem(f"[B]{_(32180)}[/B]")
    li.setProperty("IsPlayable", "false")
    xbmcplugin.addDirectoryItem(handle, url, li, isFolder=False)

    try:
        resp = client.get_all_cloud_apis(timeout=5)
        cloud_apis = resp.apis if hasattr(resp, 'apis') and resp.apis else []
    except Exception as e:
        xbmcgui.Dialog().ok(_(32030), str(e))
        xbmcplugin.endOfDirectory(handle)
        return

    if not cloud_apis:
        li = xbmcgui.ListItem(f"[{_(32084)}]")
        noop_url = _build_url(MODE_NOOP)
        xbmcplugin.addDirectoryItem(handle, noop_url, li, isFolder=False)
    else:
        for api in cloud_apis:
            name = api.name if hasattr(api, 'name') else str(api)
            url = _build_url(MODE_MOUNT_ADD, cloud_name=name)
            li = xbmcgui.ListItem(_(32075, name))
            li.setProperty("IsPlayable", "false")
            xbmcplugin.addDirectoryItem(handle, url, li, isFolder=False)

    xbmcplugin.endOfDirectory(handle)


def add_mount_dialog(cloud_name):
    """Show dialog to add a mount point for the given cloud drive."""
    dialog = xbmcgui.Dialog()
    mount_path = dialog.input(_(32076, cloud_name), f"/storage/mount/{cloud_name}")
    if not mount_path:
        return

    client = get_client()
    try:
        client.add_mount_point({"cloudName": cloud_name, "mountPath": mount_path, "sourceDir": "", "localMount": True}, timeout=10)
        dialog.notification("CloudDrive2", _(32077, cloud_name), time=3000)
    except Exception as e:
        dialog.ok(_(32030), _(32078, str(e)))


def remove_mount(cloud_name):
    """Remove a mount by cloud name."""
    client = get_client()
    try:
        client.remove_mount_point(cloud_name, timeout=10)
        xbmcgui.Dialog().notification("CloudDrive2", _(32079, cloud_name), time=3000)
    except Exception as e:
        xbmcgui.Dialog().notification("CloudDrive2", _(32080, str(e)))


def toggle_mount(cloud_name):
    """Mount or unmount a cloud drive."""
    client = get_client()
    try:
        # Check current mount state
        resp = client.get_mount_points(timeout=5)
        is_mounted = False
        if hasattr(resp, 'mountPoints') and resp.mountPoints:
            for mp in resp.mountPoints:
                name = mp.mountPoint if hasattr(mp, 'mountPoint') else ""
                if name == cloud_name:
                    is_mounted = mp.isMounted if hasattr(mp, 'isMounted') else False
                    break

        if is_mounted:
            client.unmount(cloud_name, timeout=10)
            xbmcgui.Dialog().notification("CloudDrive2", _(32082, cloud_name), time=3000)
        else:
            client.mount(cloud_name, timeout=10)
            xbmcgui.Dialog().notification("CloudDrive2", _(32081, cloud_name), time=3000)
    except Exception as e:
        xbmcgui.Dialog().ok(_(32030), _(32083, str(e)))


def restore_default_config():
    """Restore default mount point /storage/CloudDrive via CD2 API."""
    client = get_client()
    try:
        # Remove all existing mount points
        resp = client.get_mount_points(timeout=5)
        if hasattr(resp, 'mountPoints') and resp.mountPoints:
            for mp in resp.mountPoints:
                mp_path = mp.mountPoint if hasattr(mp, 'mountPoint') else ""
                if mp_path:
                    try:
                        client.unmount(mp_path, timeout=5)
                    except Exception:
                        pass
                    try:
                        client.remove_mount_point(mp_path, timeout=5)
                    except Exception:
                        pass

        # Add default mount
        client.add_mount_point({
            "name": "CloudDrive",
            "mountPoint": "/storage/CloudDrive",
            "sourceDir": "/",
            "localMount": True,
        }, timeout=10)
        # Mount it (may already be auto-mounted, ignore error)
        try:
            client.mount("/storage/CloudDrive", timeout=10)
        except Exception:
            pass
        xbmcgui.Dialog().notification("CloudDrive2", _(32179), time=5000)
    except Exception as e:
        xbmcgui.Dialog().ok(_(32030), str(e))


def _build_url(mode, **params):
    parts = [f"mode={mode}"]
    for k, v in params.items():
        parts.append(f"{k}={urllib.parse.quote(str(v))}")
    return sys.argv[0] + "?" + "&".join(parts)
