import dataclasses
from typing import Any
from collections.abc import Sequence

from debputy.manifest_parser.declarative_parser import ParserGenerator
from debputy.plugin.api.impl_types import (
    DebputyPluginMetadata,
    PackagerProvidedFileClassSpec,
    MetadataOrMaintscriptDetector,
    PluginProvidedManifestVariable,
    PluginProvidedPackageProcessor,
    PluginProvidedDiscardRule,
    ServiceManagerDetails,
    PluginProvidedKnownPackagingFile,
    PluginProvidedTypeMapping,
    PluginProvidedBuildSystemAutoDetection,
)
from debputy.plugin.api.parser_tables import (
    SUPPORTED_DISPATCHABLE_OBJECT_PARSERS,
    SUPPORTED_DISPATCHABLE_TABLE_PARSERS,
)
from debputy.plugins.debputy.to_be_api_types import BuildSystemRule


def _initialize_parser_generator() -> ParserGenerator:
    pg = ParserGenerator()

    for path, ref_doc in SUPPORTED_DISPATCHABLE_OBJECT_PARSERS.items():
        pg.add_object_parser(path, parser_documentation=ref_doc)

    for rt, path in SUPPORTED_DISPATCHABLE_TABLE_PARSERS.items():
        pg.add_table_parser(rt, path)

    return pg


@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)
    )
    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
    )
    known_packaging_files: dict[str, PluginProvidedKnownPackagingFile] = (
        dataclasses.field(default_factory=dict)
    )
    mapped_types: dict[Any, PluginProvidedTypeMapping] = dataclasses.field(
        default_factory=dict
    )
    manifest_parser_generator: ParserGenerator = dataclasses.field(
        default_factory=_initialize_parser_generator
    )
    auto_detectable_build_systems: dict[
        type[BuildSystemRule], PluginProvidedBuildSystemAutoDetection
    ] = 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
