"""Utility class to setup Fabric connections to compute resources.

More information about fabric: https://docs.fabfile.org .
"""

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    import contextlib

    with contextlib.suppress(ImportError):
        # fabric is an optional dependency, so we only do an optional import for type checking here
        from fabric import Connection  # pyright: ignore [reportMissingImports]  # noqa: PLC0415

    from slices_clientlib_aiis.schema.job import SSHInfo


def connect(ssh_info: "SSHInfo") -> "Connection":
    """Create a Fabric connection."""
    try:
        from fabric import Connection  # pyright: ignore [reportMissingImports]  # noqa: PLC0415
    except ImportError as err:
        raise ImportError("To use this function, you need to install the 'fabric' package") from err

    return Connection(
        host=ssh_info.host,
        port=ssh_info.port,
        user=ssh_info.username,
        gateway=connect(ssh_info.jump_proxy) if ssh_info.jump_proxy else None,
    )
