"""Certbot client interfaces."""
from abc import ABCMeta
from abc import abstractmethod
from argparse import ArgumentParser
import sys
from types import ModuleType
from typing import Any
from typing import Union
from typing import cast
from typing import Iterable
from typing import List
from typing import Optional
from typing import Type
from typing import TYPE_CHECKING
import warnings

import zope.interface

from acme.challenges import Challenge
from acme.challenges import ChallengeResponse
from acme.client import ClientBase
from certbot import configuration
from certbot.achallenges import AnnotatedChallenge

if TYPE_CHECKING:
    from certbot._internal.account import Account


class AccountStorage(metaclass=ABCMeta):
    """Accounts storage interface."""

    @abstractmethod
    def find_all(self) -> List['Account']:  # pragma: no cover
        """Find all accounts.

        :returns: All found accounts.
        :rtype: list

        """
        raise NotImplementedError()

    @abstractmethod
    def load(self, account_id: str) -> 'Account':  # pragma: no cover
        """Load an account by its id.

        :raises .AccountNotFound: if account could not be found
        :raises .AccountStorageError: if account could not be loaded

        :returns: The account loaded
        :rtype: .Account

        """
        raise NotImplementedError()

    @abstractmethod
    def save(self, account: 'Account', client: ClientBase) -> None:  # pragma: no cover
        """Save account.

        :raises .AccountStorageError: if account could not be saved

        """
        raise NotImplementedError()


class IConfig(zope.interface.Interface):  # pylint: disable=inherit-non-class
    """Deprecated, use certbot.configuration.NamespaceConfig instead."""


class IPluginFactory(zope.interface.Interface):  # pylint: disable=inherit-non-class
    """Deprecated, use certbot.interfaces.Plugin as ABC instead."""


class IPlugin(zope.interface.Interface):  # pylint: disable=inherit-non-class
    """Deprecated, use certbot.interfaces.Plugin as ABC instead."""


class Plugin(metaclass=ABCMeta):
    """Certbot plugin.

    Objects providing this interface will be called without satisfying
    any entry point "extras" (extra dependencies) you might have defined
    for your plugin, e.g (excerpt from ``setup.py`` script)::

      setup(
          ...
          entry_points={
              'certbot.plugins': [
                  'name=example_project.plugin[plugin_deps]',
              ],
          },
          extras_require={
              'plugin_deps': ['dep1', 'dep2'],
          }
      )

    Therefore, make sure such objects are importable and usable without
    extras. This is necessary, because CLI does the following operations
    (in order):

      - loads an entry point,
      - calls `inject_parser_options`,
      - requires an entry point,
      - creates plugin instance (`__call__`).

    """

    description: str = NotImplemented
    """Short plugin description"""

    name: str = NotImplemented
    """Unique name of the plugin"""

    @abstractmethod
    def __init__(self, config: Optional[configuration.NamespaceConfig], name: str) -> None:
        """Create a new `Plugin`.

        :param configuration.NamespaceConfig config: Configuration.
        :param str name: Unique plugin name.

        """
        super().__init__()

    @abstractmethod
    def prepare(self) -> None:
        """Prepare the plugin.

        Finish up any additional initialization.

        :raises .PluginError:
            when full initialization cannot be completed.
        :raises .MisconfigurationError:
            when full initialization cannot be completed. Plugin will
            be displayed on a list of available plugins.
        :raises .NoInstallationError:
            when the necessary programs/files cannot be located. Plugin
            will NOT be displayed on a list of available plugins.
        :raises .NotSupportedError:
            when the installation is recognized, but the version is not
            currently supported.

        """

    @abstractmethod
    def more_info(self) -> str:
        """Human-readable string to help the user.

        Should describe the steps taken and any relevant info to help the user
        decide which plugin to use.

        :rtype str:

        """

    @classmethod
    @abstractmethod
    def inject_parser_options(cls, parser: ArgumentParser, name: str) -> None:
        """Inject argument parser options (flags).

        1. Be nice and prepend all options and destinations with
        `~.common.option_namespace` and `~common.dest_namespace`.

        2. Inject options (flags) only. Positional arguments are not
        allowed, as this would break the CLI.

        :param ArgumentParser parser: (Almost) top-level CLI parser.
        :param str name: Unique plugin name.

        """


class IAuthenticator(IPlugin):  # pylint: disable=inherit-non-class
    """Deprecated, use certbot.interfaces.Authenticator as ABC instead."""


class Authenticator(Plugin):
    """Generic Certbot Authenticator.

    Class represents all possible tools processes that have the
    ability to perform challenges and attain a certificate.

    """

    @abstractmethod
    def get_chall_pref(self, domain: str) -> Iterable[Type[Challenge]]:
        """Return `collections.Iterable` of challenge preferences.

        :param str domain: Domain for which challenge preferences are sought.

        :returns: `collections.Iterable` of challenge types (subclasses of
            :class:`acme.challenges.Challenge`) with the most
            preferred challenges first. If a type is not specified, it means the
            Authenticator cannot perform the challenge.
        :rtype: `collections.Iterable`

        """

    @abstractmethod
    def perform(self, achalls: List[AnnotatedChallenge]) -> List[ChallengeResponse]:
        """Perform the given challenge.

        :param list achalls: Non-empty (guaranteed) list of
            :class:`~certbot.achallenges.AnnotatedChallenge`
            instances, such that it contains types found within
            :func:`get_chall_pref` only.

        :returns: list of ACME
            :class:`~acme.challenges.ChallengeResponse` instances corresponding to each provided
            :class:`~acme.challenges.Challenge`.
        :rtype: :class:`collections.List` of
            :class:`acme.challenges.ChallengeResponse`,
            where responses are required to be returned in
            the same order as corresponding input challenges

        :raises .PluginError: If some or all challenges cannot be performed

        """

    @abstractmethod
    def cleanup(self, achalls: List[AnnotatedChallenge]) -> None:
        """Revert changes and shutdown after challenges complete.

        This method should be able to revert all changes made by
        perform, even if perform exited abnormally.

        :param list achalls: Non-empty (guaranteed) list of
            :class:`~certbot.achallenges.AnnotatedChallenge`
            instances, a subset of those previously passed to :func:`perform`.

        :raises PluginError: if original configuration cannot be restored

        """


class IInstaller(IPlugin):  # pylint: disable=inherit-non-class
    """Deprecated, use certbot.interfaces.Installer as ABC instead."""


class Installer(Plugin):
    """Generic Certbot Installer Interface.

    Represents any server that an X509 certificate can be placed.

    It is assumed that :func:`save` is the only method that finalizes a
    checkpoint. This is important to ensure that checkpoints are
    restored in a consistent manner if requested by the user or in case
    of an error.

    Using :class:`certbot.reverter.Reverter` to implement checkpoints,
    rollback, and recovery can dramatically simplify plugin development.

    """

    @abstractmethod
    def get_all_names(self) -> Iterable[str]:
        """Returns all names that may be authenticated.

        :rtype: `collections.Iterable` of `str`

        """

    @abstractmethod
    def deploy_cert(self, domain: str, cert_path: str, key_path: str,
                    chain_path: str, fullchain_path: str) -> None:
        """Deploy certificate.

        :param str domain: domain to deploy certificate file
        :param str cert_path: absolute path to the certificate file