from pathlib import Path
from tempfile import TemporaryDirectory
from typing import Dict, Optional, Sequence

from .types import Assembly, Runtime, RuntimeInfo
from .util import StrOrPath
from .util.find import find_dotnet_root, find_libmono, find_runtimes
from .util.runtime_spec import DotnetCoreRuntimeSpec

__all__ = [
    "get_mono",
    "get_netfx",
    "get_coreclr",
    "find_dotnet_root",
    "find_libmono",
    "find_runtimes",
    "Runtime",
    "Assembly",
    "RuntimeInfo",
    "DotnetCoreRuntimeSpec",
]


def get_mono(
    *,
    # domain: Optional[str] = None,
    config_file: Optional[StrOrPath] = None,
    global_config_file: Optional[StrOrPath] = None,
    libmono: Optional[StrOrPath] = None,
    sgen: bool = True,
    debug: bool = False,
    jit_options: Optional[Sequence[str]] = None,
    assembly_dir: Optional[str] = None,
    config_dir: Optional[str] = None,
    set_signal_chaining: bool = False,
) -> Runtime:
    """Get a Mono runtime instance

    :param config_file:
        Path to the domain configuration file
    :param global_config_file:
        Path to the global configuration file to load (defaults to, e.g.,
        ``/etc/mono/config``)
    :param libmono:
        Path to the Mono runtime dll/so/dylib. If this is not specified, we try
        to discover a globally installed instance using :py:func:`find_libmono`
    :param sgen:
        If ``libmono`` is not specified, this is passed to
        :py:func:`find_libmono`
    :param debug:
        Whether to initialise Mono debugging
    :param jit_options:
        "Command line options" passed to Mono's ``mono_jit_parse_options``
    :param assembly_dir:
        The base directory for assemblies, passed to ``mono_set_dirs``
    :param config_dir:
        The base directory for configuration files, passed to ``mono_set_dirs``
    :param set_signal_chaining:
        Whether to enable signal chaining, passed to ``mono_set_signal_chaining``.
        If it is enabled, the runtime saves the original signal handlers before
        installing its own, and calls the original ones in the following cases:
            - SIGSEGV/SIGABRT while executing native code
            - SIGPROF
            - SIGFPE
            - SIGQUIT
            - SIGUSR2
        This currently only works on POSIX platforms
    """
    from .mono import Mono

    libmono = _maybe_path(libmono)
    if libmono is None:
        libmono = find_libmono(sgen=sgen, assembly_dir=assembly_dir)

    impl = Mono(
        # domain=domain,
        debug=debug,
        jit_options=jit_options,
        config_file=_maybe_path(config_file),
        global_config_file=_maybe_path(global_config_file),
        libmono=libmono,
        assembly_dir=assembly_dir,
        config_dir=config_dir,
        set_signal_chaining=set_signal_chaining,
    )
    return impl


def get_coreclr(
    *,
    runtime_config: Optional[StrOrPath] = None,
    dotnet_root: Optional[StrOrPath] = None,
    properties: Optional[Dict[str, str]] = None,
    runtime_spec: Optional[DotnetCoreRuntimeSpec] = None,
) -> Runtime:
    """Get a CoreCLR (.NET Core) runtime instance

    The returned ``DotnetCoreRuntime`` also acts as a mapping of the config
    properties. They can be retrieved using the index operator and can be
    written until the runtime is initialized. The runtime is initialized when
    the first function object is retrieved.

    :param runtime_config:
        Pass to a ``runtimeconfig.json`` as generated by
        ``dotnet publish``. If this parameter is not given, a temporary runtime
        config will be generated.
    :param dotnet_root:
        The root directory of the .NET Core installation. If this is not
        specified, we try to discover it using :py:func:`find_dotnet_root`.
    :param properties:
        Additional runtime properties. These can also be passed using the
        ``configProperties`` section in the runtime config.
    :param runtime_spec:
        If the ``runtime_config`` is not specified, the concrete runtime to use
        can be controlled by passing this parameter. Possible values can be
        retrieved using :py:func:`find_runtimes`."""
    from .hostfxr import DotnetCoreRuntime

    dotnet_root = _maybe_path(dotnet_root)
    if dotnet_root is None:
        dotnet_root = find_dotnet_root()

    temp_dir = None
    runtime_config = _maybe_path(runtime_config)
    if runtime_config is None:
        if runtime_spec is None:
            candidates = [
                rt for rt in find_runtimes() if rt.name == "Microsoft.NETCore.App"
            ]
            candidates.sort(key=lambda spec: spec.version, reverse=True)
            if not candidates:
                raise RuntimeError("Failed to find a suitable runtime")

            runtime_spec = candidates[0]

        temp_dir = TemporaryDirectory()
        runtime_config = Path(temp_dir.name) / "runtimeconfig.json"

        with open(runtime_config, "w") as f:
            runtime_spec.write_config(f)

    impl = DotnetCoreRuntime(runtime_config=runtime_config, dotnet_root=dotnet_root)
    if properties:
        for key, value in properties.items():
            impl[key] = value

    if temp_dir:
        temp_dir.cleanup()

    return impl


def get_netfx(
    *, domain: Optional[str] = None, config_file: Optional[StrOrPath] = None
) -> Runtime:
    """Get a .NET Framework runtime instance

    :param domain:
        Name of the domain to create. If no value is passed, assemblies will be
        loaded into the root domain.
    :param config_file:
        Configuration file to use to initialize the ``AppDomain``. This will
        only be used for non-root-domains as we can not control the
        configuration of the implicitly loaded root domain.
    """
    from .netfx import NetFx

    impl = NetFx(domain=domain, config_file=_maybe_path(config_file))
    return impl


def _maybe_path(p: Optional[StrOrPath]) -> Optional[Path]:
    if p is None:
        return None
    else:
        return Path(p)
