import os
import sys
from typing import Mapping

import pytest
from debian.deb822 import Deb822
from debian.debian_support import DpkgArchTable

from debputy._deb_options_profiles import DebOptionsAndProfiles
from debputy.architecture_support import (
    DpkgArchitectureBuildProcessValuesTable,
    faked_arch_table,
)
from debputy.packages import BinaryPackage
from debputy.plugin.debputy.debputy_plugin import initialize_debputy_features
from debputy.plugin.api.impl import (
    PluginProvidedFeatureSet,
    DebputyPluginInitializerProvider,
    DebputyPluginMetadata,
)
from debputy.substitution import NULL_SUBSTITUTION, Substitution


# Disable dpkg's translation layer.  It is very slow and disabling it makes it easier to debug
# test-failure reports from systems with translations active.
os.environ["DPKG_NLS"] = "0"

# Tests expect to be able to load `testplugin` as python module via the plugin load API.
sys.path.insert(0, os.path.dirname(__file__))


@pytest.fixture(scope="session")
def amd64_dpkg_architecture_variables() -> DpkgArchitectureBuildProcessValuesTable:
    return faked_arch_table("amd64")


@pytest.fixture(scope="session")
def dpkg_arch_query() -> DpkgArchTable:
    return DpkgArchTable.load_arch_table()


@pytest.fixture()
def package_single_foo_arch_all_cxt_amd64(
    amd64_dpkg_architecture_variables,
    dpkg_arch_query,
) -> Mapping[str, BinaryPackage]:
    return {
        p.name: p
        for p in [
            BinaryPackage(
                Deb822(
                    {
                        "Package": "foo",
                        "Architecture": "all",
                    }
                ),
                amd64_dpkg_architecture_variables,
                dpkg_arch_query,
                is_main_package=True,
            )
        ]
    }


@pytest.fixture(scope="session")
def null_substitution() -> Substitution:
    return NULL_SUBSTITUTION


@pytest.fixture(scope="session")
def no_profiles_or_build_options() -> DebOptionsAndProfiles:
    return DebOptionsAndProfiles(environ={})


@pytest.fixture(scope="session")
def debputy_plugin_feature_set() -> PluginProvidedFeatureSet:
    plugin_metadata = DebputyPluginMetadata(
        plugin_name="debputy (test)",
        plugin_version="0.0.1-test",
        api_compat_version=1,
        plugin_initializer=initialize_debputy_features,
        plugin_loader=None,
    )
    feature_set = PluginProvidedFeatureSet(
        plugin_data={},
        packager_provided_files={},
        metadata_maintscript_detectors={},
    )
    api = DebputyPluginInitializerProvider(plugin_metadata, feature_set)
    api.load_plugin()
    return feature_set
