import dataclasses
import os.path
from typing import (
    Optional,
    Callable,
    FrozenSet,
    Dict,
    List,
    Tuple,
    Generic,
    TYPE_CHECKING,
    TypeVar,
    Iterable,
    cast,
    Any,
    Sequence,
    Union,
    Type,
    TypedDict,
)

from debputy.exceptions import (
    DebputyFSIsROError,
    PluginAPIViolationError,
    PluginConflictError,
    UnhandledOrUnexpectedErrorFromPluginError,
)
from debputy.filesystem_scan import PathDef, as_path_def
from debputy.installations import InstallRule
from debputy.maintscript_snippet import DpkgMaintscriptHelperCommand
from debputy.manifest_conditions import ManifestCondition
from debputy.manifest_parser.exceptions import ManifestParseException
from debputy.manifest_parser.util import AttributePath
from debputy.packages import BinaryPackage
from debputy.plugin.api import (
    VirtualPath,
    BinaryCtrlAccessor,
    PackageProcessingContext,
)
from debputy.plugin.api.spec import (
    DebputyPluginInitializer,
    MetadataAutoDetector,
    DpkgTriggerType,
    ParserDocumentation,
    PackageProcessor,
)
from debputy.substitution import VariableContext
from debputy.transformation_rules import TransformationRule
from debputy.util import _normalize_path

if TYPE_CHECKING:
    from debputy.plugin.api.spec import (
        ServiceDetector,
        ServiceIntegrator,
        PackageTypeSelector,
    )
    from debputy.manifest_parser.parser_data import ParserContextData
    from debputy.highlevel_manifest import (
        HighLevelManifest,
        PackageTransformationDefinition,
    )


_PACKAGE_TYPE_DEB_ONLY = frozenset(["deb"])
_ALL_PACKAGE_TYPES = frozenset(["deb", "udeb"])


TD = TypeVar("TD", bound="DebputyParsedContent")
PF = TypeVar("PF")
SF = TypeVar("SF")
TP = TypeVar("TP")
TTP = Type[TP]

DIPKWHandler = Callable[[str, AttributePath, "ParserContextData"], TP]
DIPHandler = Callable[[str, PF, AttributePath, "ParserContextData"], TP]


def resolve_package_type_selectors(
    package_type: "PackageTypeSelector",
) -> FrozenSet[str]:
    if package_type is _ALL_PACKAGE_TYPES or package_type is _PACKAGE_TYPE_DEB_ONLY:
        return cast("FrozenSet[str]", package_type)
    if isinstance(package_type, str):
        return (
            _PACKAGE_TYPE_DEB_ONLY
            if package_type == "deb"
            else frozenset([package_type])
        )
    else:
        return frozenset(package_type)


@dataclasses.dataclass(slots=True)
class DebputyPluginMetadata:
    plugin_name: str
    api_compat_version: int
    plugin_loader: Optional[Callable[[], Callable[["DebputyPluginInitializer"], None]]]
    plugin_initializer: Optional[Callable[["DebputyPluginInitializer"], None]]
    plugin_path: str
    _is_initialized: bool = False

    @property
    def is_loaded(self) -> bool:
        return self.plugin_initializer is not None

    @property
    def is_initialized(self) -> bool:
        return self._is_initialized

    def initialize_plugin(self, api: "DebputyPluginInitializer") -> None:
        if self.is_initialized:
            raise RuntimeError("Cannot load plugins twice")
        if not self.is_loaded:
            self.load_plugin()
        plugin_initializer = self.plugin_initializer
        assert plugin_initializer is not None
        plugin_initializer(api)
        self._is_initialized = True

    def load_plugin(self) -> None:
        plugin_loader = self.plugin_loader
        assert plugin_loader is not None
        self.plugin_initializer = plugin_loader()
        assert self.plugin_initializer is not None


@dataclasses.dataclass(slots=True, frozen=True)
class PluginProvidedParser(Generic[PF, TP]):
    parser: "DeclarativeInputParser[PF]"
    handler: Callable[[str, PF, "AttributePath", "ParserContextData"], TP]
    plugin_metadata: DebputyPluginMetadata

    def parse(
        self,
        name: str,
        value: object,
        attribute_path: "AttributePath",
        *,
        parser_context: "ParserContextData",
    ) -> TP:
        parsed_value = self.parser.parse_input(
            value, attribute_path, parser_context=parser_context
        )
        return self.handler(name, parsed_value, attribute_path, parser_context)


class PPFFormatParam(TypedDict):
    priority: Optional[int]
    name: str
    owning_package: str


@dataclasses.dataclass(slots=True, frozen=True)
class PackagerProvidedFileClassSpec:
    debputy_plugin_metadata: DebputyPluginMetadata
    stem: str
    installed_as_format: str
    default_mode: int
    default_priority: Optional[int]
    allow_name_segment: bool
    allow_architecture_segment: bool
    post_formatting_rewrite: Optional[Callable[[str], str]]
    packageless_is_fallback_for_all_packages: bool
    reservation_only: bool
    formatting_callback: Optional[
        Callable[[str, PPFFormatParam, VirtualPath], str]
    ] = None

    @property
    def supports_priority(self) -> bool:
        return self.default_priority is not None

    def compute_dest(
        self,
        assigned_name: str,
        # Note this method is currently used 1:1 inside plugin tests.
        *,
        owning_package: Optional[str] = None,
        assigned_priority: Optional[int] = None,
        path: Optional[VirtualPath] = None,
    ) -> Tuple[str, str]:
        if assigned_priority is not None and not self.supports_priority:
            raise ValueError(
                f"Cannot assign priority to packager provided files with stem"
                f' "{self.stem}" (e.g., "debian/foo.{self.stem}"). They'
                " do not use priority at all."
            )

        path_format = self.installed_as_format
        if self.supports_priority and assigned_priority is None:
            assigned_priority = self.default_priority

        if owning_package is None:
            owning_package = assigned_name

        params: PPFFormatParam = {
            "priority": assigned_priority,
            "name": assigned_name,
            "owning_package": owning_package,
        }

        if self.formatting_callback is not None:
            if path is None:
                raise ValueError(
                    "The path parameter is required for PPFs with formatting_callback"
                )
            path = self.formatting_callback(path_format, params, path)
        else:
            path = path_format.format(**params)

        dirname, basename = os.path.split(path)
        dirname = _normalize_path(dirname)

        if self.post_formatting_rewrite:
            basename = self.post_formatting_rewrite(basename)
        return dirname, basename


@dataclasses.dataclass(slots=True)
class MetadataOrMaintscriptDetector:
    plugin_metadata: DebputyPluginMetadata
    detector_id: str
    detector: MetadataAutoDetector
    applies_to_package_types: FrozenSet[str]
    enabled: bool = True

    def applies_to(self, binary_package: BinaryPackage) -> bool:
        return binary_package.package_type in self.applies_to_package_types

    def run_detector(
        self,
        fs_root: "VirtualPath",
        ctrl: "BinaryCtrlAccessor",
        context: "PackageProcessingContext",
    ) -> None:
        try:
            self.detector(fs_root, ctrl, context)
        except DebputyFSIsROError as e:
            nv = self.plugin_metadata.plugin_name
            raise PluginAPIViolationError(
                f'The plugin {nv} violated the API contract for "metadata detectors"'
                " by attempting to mutate the provided file system in its metadata detector"
                f" with id {self.detector_id}.  File system mutation is *not* supported at"
                " this stage (file system layout is committed and the attempted changes"
                " would be lost)."
            ) from e
        except (ChildProcessError, RuntimeError, AttributeError) as e:
            nv = f"{self.plugin_metadata.plugin_name}"
            raise UnhandledOrUnexpectedErrorFromPluginError(
                f"The plugin {nv} threw an unhandled or unexpected exception from its metadata"
                f" detector with id {self.detector_id}."
            ) from e


class DeclarativeInputParser(Generic[TD]):
    @property
    def inline_reference_documentation(self) -> Optional[ParserDocumentation]:
        return None

    @property
    def reference_documentation_url(self) -> Optional[str]:
        doc = self.inline_reference_documentation
        return doc.documentation_reference_url if doc is not None else None

    def parse_input(
        self,
        value: object,
        path: "AttributePath",
        *,
        parser_context: Optional["ParserContextData"] = None,
    ) -> TD:
        raise NotImplementedError


class DispatchingParser(Generic[TP]):
    def __init__(self, base_type: TTP, manifest_attribute_path: str) -> None:
        self.base_type = base_type
        self.manifest_attribute_path = manifest_attribute_path
        self._parsers: Dict[str, PluginProvidedParser[Any, TP]] = {}

    def is_known_keyword(self, keyword: str) -> bool:
        return keyword in self._parsers

    def registered_keywords(self) -> Iterable[str]:
        yield from self._parsers

    def parser_for(self, keyword: str) -> PluginProvidedParser[Any, TP]:
        return self._parsers[keyword]

    def parse(
        self,
        orig_value: object,
        attribute_path: "AttributePath",
        *,
        parser_context: "ParserContextData",
    ) -> TP:
        if isinstance(orig_value, str):
            key = orig_value
            value = None
            value_path = attribute_path
        elif isinstance(orig_value, dict):
            if len(orig_value) != 1:
                valid_keys = ", ".join(sorted(self._parsers.keys()))
                raise ManifestParseException(
                    f'The mapping "{attribute_path.path}" had two keys, but it should only have one top level key.'
                    " Maybe you are missing a list marker behind the second key or some indentation.  The"
                    f" possible keys are: {valid_keys}"
                )
            key, value = next(iter(orig_value.items()))
            value_path = attribute_path[key]
        else:
            raise ManifestParseException(
                f"The attribute {attribute_path.path} must be a string or a mapping."
            )
        provided_parser = self._parsers.get(key)
        if provided_parser is None:
            valid_keys = ", ".join(sorted(self._parsers.keys()))
            raise ManifestParseException(
                f'Unknown or unsupported action "{key}" at {value_path.path}.'
                " Valid options at this location are keys:"
                f" {valid_keys}"
            )
        return provided_parser.parse(
            key, value, value_path, parser_context=parser_context
        )

    def register_keyword(
        self,
        keyword: Union[str, Sequence[str]],
        handler: DIPKWHandler,
        plugin_metadata: DebputyPluginMetadata,
        *,
        inline_reference_documentation: Optional[ParserDocumentation] = None,
    ) -> None:
        reference_documentation_url = None
        if inline_reference_documentation:
            if inline_reference_documentation.attribute_doc:
                raise ValueError(
                    "Cannot provide per-attribute documentation for a value-less keyword!"
                )
            if inline_reference_documentation.alt_parser_description:
                raise ValueError(
                    "Cannot provide non-mapping-format documentation for a value-less keyword!"
                )
            reference_documentation_url = (
                inline_reference_documentation.documentation_reference_url
            )
        parser = DeclarativeValuelessKeywordInputParser(
            inline_reference_documentation,
            documentation_reference=reference_documentation_url,
        )

        def _combined_handler(
            name: str,
            _ignored: Any,
            attr_path: AttributePath,
            context: "ParserContextData",
        ) -> TP:
            return handler(name, attr_path, context)

        p = PluginProvidedParser(
            parser,
            _combined_handler,
            plugin_metadata,
        )

        self._add_parser(keyword, p)

    def register_parser(
        self,
        keyword: Union[str, List[str]],
        parser: "DeclarativeInputParser[PF, TP]",
        handler: Callable[[str, PF, "AttributePath", "ParserContextData"], TP],
        plugin_metadata: DebputyPluginMetadata,
    ) -> None:
        p = PluginProvidedParser(
            parser,
            handler,
            plugin_metadata,
        )
        self._add_parser(keyword, p)

    def _add_parser(
        self,
        keyword: Union[str, List[str]],
        ppp: "PluginProvidedParser[PF, TP]",
    ) -> None:
        ks = [keyword] if isinstance(keyword, str) else keyword
        for k in ks:
            existing_parser = self._parsers.get(k)
            if existing_parser is not None:
                message = (
                    f'The rule name "{k}" for {self.base_type.__name__} is already taken by'
                    f" the plugin {existing_parser.plugin_metadata.plugin_name}. This conflict was triggered"
                    f" when plugin {ppp.plugin_metadata.plugin_name} attempted to register its parser."
                )
                raise PluginConflictError(
                    message,
                    existing_parser.plugin_metadata,
                    ppp.plugin_metadata,
                )
            self._parsers[k] = ppp


@dataclasses.dataclass(slots=True)
class DeclarativeValuelessKeywordInputParser(DeclarativeInputParser[None]):
    inline_reference_documentation: Optional[ParserDocumentation] = None
    documentation_reference: Optional[str] = None

    def parse_input(
        self,
        value: object,
        path: "AttributePath",
        *,
        parser_context: Optional["ParserContextData"] = None,
    ) -> TD:
        if value is None:
            return cast("TD", value)
        if self.documentation_reference is not None:
            doc_ref = f" (Documentation: {self.documentation_reference})"
        else:
            doc_ref = ""
        raise ManifestParseException(
            f"Expected attribute {path.path} to be a string.{doc_ref}"
        )


SUPPORTED_DISPATCHABLE_PARSERS = {
    InstallRule: "installations",
    TransformationRule: "packages.<PKGNAME>.transformations",
    DpkgMaintscriptHelperCommand: "packages.<PKGNAME>.conffile-management",
    ManifestCondition: "*.when",
}


@dataclasses.dataclass(slots=True)
class PluginProvidedManifestVariable:
    plugin_metadata: DebputyPluginMetadata
    variable_name: str
    variable_value: Optional[Union[str, Callable[[VariableContext], str]]]
    is_context_specific_variable: bool
    variable_reference_documentation: Optional[str] = None
    is_documentation_placeholder: bool = False
    is_for_special_case: bool = False

    _variable_value_cache: Optional[str] = None

    @property
    def is_internal(self) -> bool:
        return self.variable_name.startswith("_") or ":_" in self.variable_name

    @property
    def is_token(self) -> bool:
        return self.variable_name.startswith("token:")

    def resolve(self, variable_context: VariableContext) -> str:
        res = self._variable_value_cache
        if res is None:
            value_resolver = self.variable_value
            if isinstance(value_resolver, str):
                res = value_resolver
            else:
                res = value_resolver(variable_context)
            self.variable_value = res
        return res


@dataclasses.dataclass(slots=True, frozen=True)
class AutomaticDiscardRuleExample:
    content: Sequence[Tuple[PathDef, bool]]
    description: Optional[str] = None


def automatic_discard_rule_example(
    *content: Union[str, PathDef, Tuple[Union[str, PathDef], bool]],
    example_description: Optional[str] = None,
) -> AutomaticDiscardRuleExample:
    """Provide an example for an automatic discard rule

    The return value of this method should be passed to the `examples` parameter of
    `automatic_discard_rule` method - either directly for a single example or as a
    part of a sequence of examples.

    >>> # Possible example for an exclude rule for ".la" files
    >>> # Example shows two files; The ".la" file that will be removed and another file that
    >>> # will be kept.
    >>> automatic_discard_rule_example(   # doctest: +ELLIPSIS
    ...     "usr/lib/libfoo.la",
    ...     ("usr/lib/libfoo.so.1.0.0", False),
    ... )
    AutomaticDiscardRuleExample(...)

    Keep in mind that you have to explicitly include directories that are relevant for the test
    if you want them shown. Also, if a directory is excluded, all path beneath it will be
    automatically excluded in the example as well. Your example data must account for that.

    >>> # Possible example for python cache file discard rule
    >>> # In this example, we explicitly list the __pycache__ directory itself because we
    >>> # want it shown in the output (otherwise, we could have omitted it)
    >>> automatic_discard_rule_example(   # doctest: +ELLIPSIS
    ...     (".../foo.py", False),
    ...     ".../__pycache__/",
    ...     ".../__pycache__/...",
    ...     ".../foo.pyc",
    ...     ".../foo.pyo",
    ... )
    AutomaticDiscardRuleExample(...)

    Note: Even if `__pycache__` had been implicit, the result would have been the same. However,
    the rendered example would not have shown the directory on its own.  The use of `...` as
    path names is useful for denoting "anywhere" or "anything". Though, there is nothing "magic"
    about this name - it happens to be allowed as a path name (unlike `.` or `..`).

    These examples can be seen via `debputy plugin show automatic-discard-rules <name-here>`.

    :param content: The content of the example.  Each element can be either a path definition or
      a tuple of a path definition followed by a verdict (boolean). Each provided path definition
      describes the paths to be presented in the example. Implicit paths such as parent
      directories will be created but not shown in the example.  Therefore, if a directory is
      relevant to the example, be sure to explicitly list it.

      The verdict associated with a path determines whether the path should be discarded (when
      True) or kept (when False). When a path is not explicitly associated with a verdict, the
      verdict is assumed to be discarded (True).
    :param example_description: An optional description displayed together with the example.
    :return: An opaque data structure containing the example.
    """
    example = []
    for d in content:
        if not isinstance(d, tuple):
            pd = d
            verdict = True
        else:
            pd, verdict = d

        path_def = as_path_def(pd)
        example.append((path_def, verdict))

    if not example:
        raise ValueError("At least one path must be given for an example")

    return AutomaticDiscardRuleExample(
        tuple(example),
        description=example_description,
    )


@dataclasses.dataclass(slots=True, frozen=True)
class PluginProvidedPackageProcessor:
    processor_id: str
    applies_to_package_types: FrozenSet[str]
    package_processor: PackageProcessor
    dependencies: FrozenSet[Tuple[str, str]]
    plugin_metadata: DebputyPluginMetadata

    def applies_to(self, binary_package: BinaryPackage) -> bool:
        return binary_package.package_type in self.applies_to_package_types

    @property
    def dependency_id(self) -> Tuple[str, str]:
        return self.plugin_metadata.plugin_name, self.processor_id


@dataclasses.dataclass(slots=True, frozen=True)
class PluginProvidedDiscardRule:
    name: str
    plugin_metadata: DebputyPluginMetadata
    discard_check: Callable[[VirtualPath], bool]
    reference_documentation: Optional[str]
    examples: Sequence[AutomaticDiscardRuleExample] = tuple()

    def should_discard(self, path: VirtualPath) -> bool:
        return self.discard_check(path)


@dataclasses.dataclass(slots=True, frozen=True)
class ServiceManagerDetails:
    service_manager: str
    service_detector: "ServiceDetector"
    service_integrator: "ServiceIntegrator"
    plugin_metadata: DebputyPluginMetadata


@dataclasses.dataclass(slots=True)
class PluginProvidedFeatureSet:
    plugin_data: Dict[str, DebputyPluginMetadata] = dataclasses.field(
        default_factory=dict
    )
    packager_provided_files: Dict[
        str, PackagerProvidedFileClassSpec
    ] = dataclasses.field(default_factory=dict)
    metadata_maintscript_detectors: Dict[
        str, List[MetadataOrMaintscriptDetector]
    ] = dataclasses.field(default_factory=dict)
    dispatchable_parsers: Dict[TTP, "DispatchingParser[TP]"] = dataclasses.field(
        default_factory=lambda: {
            rt: DispatchingParser(rt, path)
            for rt, path in SUPPORTED_DISPATCHABLE_PARSERS.items()
        }
    )
    manifest_variables: Dict[str, PluginProvidedManifestVariable] = dataclasses.field(
        default_factory=dict
    )
    all_package_processors: Dict[
        Tuple[str, str], PluginProvidedPackageProcessor
    ] = dataclasses.field(default_factory=dict)
    auto_discard_rules: Dict[str, PluginProvidedDiscardRule] = dataclasses.field(
        default_factory=dict
    )
    service_managers: Dict[str, ServiceManagerDetails] = dataclasses.field(
        default_factory=dict
    )

    def package_processors_in_order(self) -> Sequence[PluginProvidedPackageProcessor]:
        order = []
        delayed = []
        for plugin_processor in self.all_package_processors.values():
            if not plugin_processor.dependencies:
                order.append(plugin_processor)
            else:
                delayed.append(plugin_processor)

        # At the time of writing, insert order will work as a plugin cannot declare
        # dependencies out of order in the current version.  However, we want to
        # ensure dependencies are taken a bit seriously, so we ensure that processors
        # without dependencies are run first.  This should weed out anything that
        # needs dependencies but do not add them.
        #
        # It is still far from as any dependency issues will be hidden if you just
        # add a single dependency.
        order.extend(delayed)
        return order


class PackageProcessingContextProvider(PackageProcessingContext):
    __slots__ = ("_manifest", "_binary_package", "_related_udeb_package")

    def __init__(
        self,
        manifest: "HighLevelManifest",
        binary_package: BinaryPackage,
        related_udeb_package: Optional[BinaryPackage],
    ) -> None:
        self._manifest = manifest
        self._binary_package = binary_package
        self._related_udeb_package = related_udeb_package

    def _package_state_for(
        self,
        package: BinaryPackage,
    ) -> "PackageTransformationDefinition":
        return self._manifest.package_state_for(package.name)

    def _package_version_for(
        self,
        package: BinaryPackage,
    ) -> str:
        package_state = self._package_state_for(package)
        version = package_state.binary_version
        if version is not None:
            return version
        return self._manifest.source_version(
            include_binnmu_version=not package.is_arch_all
        )

    @property
    def binary_package(self) -> BinaryPackage:
        return self._binary_package

    @property
    def related_udeb_package(self) -> Optional[BinaryPackage]:
        return self._related_udeb_package

    @property
    def binary_package_version(self) -> str:
        return self._package_version_for(self._binary_package)

    @property
    def related_udeb_package_version(self) -> Optional[str]:
        udeb = self._related_udeb_package
        if udeb is None:
            return None
        return self._package_version_for(udeb)


@dataclasses.dataclass(slots=True, frozen=True)
class PluginProvidedTrigger:
    dpkg_trigger_type: DpkgTriggerType
    dpkg_trigger_target: str
    provider: DebputyPluginMetadata
    provider_source_id: str

    def serialized_format(self) -> str:
        return f"{self.dpkg_trigger_type} {self.dpkg_trigger_target}"
