import collections
import functools
from unittest.mock import Mock, sentinel

import keyring
import pytest
from gitubuntu.git_repository import HeadInfoItem
import gitubuntu.source_information as target
from gitubuntu.source_information import derive_codename_from_series
from gitubuntu import source_information


def test_keyring_backend_found():
    """Test that the keyring module can find a suitable backend

    In LP: #1794041, keyring 15.0.0 removed keyring.util.escape; keyrings.alt
    started using its own version in keyrings.alt 3.1. Since git-ubuntu's
    setup.py mandated keyrings.alt 2.3 but specified no requirement for keyring
    itself, this led to an old keyrings.alt being used against a newer
    keyring, which failed because keyring.util.escape was no longer defined
    anywhere.

    The real requirement we have is that _some_ keyring is available. Since the
    keyring module might choose any backend, the real test we need here is to
    ensure that the keyring module didn't fail to find any backend. It has a
    specific "fail" backend for this, so we test here that this isn't the one
    it "found".

    Unfortunately this is a little brittle in case backend arrangements inside
    the keyring module changes, but there doesn't seem to be specified
    mechanism in the API to determine if a backend keyring has been found
    successfully.
    """
    k = keyring.get_keyring()
    assert not isinstance(k, keyring.backends.fail.Keyring)


@pytest.mark.parametrize('codename', [
    'eoan',
    'feisty',
    'sid',
    'bionic'
])
def test_derive_codename_from_series_as_codenames(codename):
    """Test that series names matching codenames return the codename

    For both Debian and Ubuntu, when looking up the codename for
    a series, if we passed in a codename verify that codename gets
    returned, as expected.
    """
    assert derive_codename_from_series(codename) == codename


@pytest.mark.parametrize('alias,codename', [
    ('unstable', 'sid'),
    ('experimental', 'experimental')
])
def test_derive_codename_from_series_as_aliases(alias, codename):
    """Test that aliases as series names are converted to codenames

    Debian (only) allows using aliases for codenames, such as stable,
    unstable, and so on.  The aliases can be pointed at different
    codenames over time as things develop, however two aliases, unstable
    and experimental, always point consistently to specific codenames
    (sid and experimental, respectively).  This test verifies that the
    alias conversion works as expected for these two special cases.
    """
    assert derive_codename_from_series(alias) == codename


@pytest.mark.parametrize('bad_codename', [
    None,
    0,
    123,
    '',
    '0',
    '12345',
    'invalid',
    'beaver',
    'dapper hardy lucid precise trusty xenial bionic',
    'buster buster buster',
    'stablestable'
    ])
def test_derive_codename_from_invalid_series(bad_codename):
    """Tests that passing erroneous values raises expected ValueError exception"""
    with pytest.raises(ValueError):
        derive_codename_from_series(bad_codename)


@pytest.mark.parametrize('series,codename', [
    ('unstable', 'sid'),
    ('experimental', 'experimental'),
    ('bionic', 'bionic'),
    ])
def test_derive_codename_from_broken_distro_info(monkeypatch, series, codename):
    """Test for proper lookup of Ubuntu codenames

    Coverity discovered a cut-and-paste error in
    derive_codename_from_series() where Ubuntu codenames were being
    looked up against Debian instead of Ubuntu.  Fortunately,
    DistroInfo's codename() implementation simply returns codenames it
    doesn't recognize, so in practice the behavior would work as
    expected.  However, we can't count on DistroInfo's permissiveness.

    This test uses a stricter implementation of DebianDistroInfo that
    refuses to pass-thru incorrect codenames.
    """
    MockDistroRelease = collections.namedtuple(
        'MockDistroRelease', 'version,codename,series,created,release,eol'
    )

    class MockDebianDistroInfo:
        """A simplified version of DebianDistroInfo with hardcoded data

        This mock provides a reduced implementation of DebianDistroInfo,
        with the release CSV information included directly in the class
        rather than loading from an external file.

        Additionally, it provides a stricter implementation of the
        codename() routine that throws an exception when looking up
        invalid release names.
        """
        def __init__(self):
            # Snipped data from distro-info-data
            data = [
                '3.0,Woody,woody,2000-08-15,2002-07-19,2006-06-30',
                '6.0,Squeeze,squeeze,2009-02-14,2011-02-06,2014-05-31',
                '9,Stretch,stretch,2015-04-25,2017-06-17,',
                '12,Bookworm,bookworm,2021-08-01,,',
                ',Sid,sid,1993-08-16,,',
                ',Experimental,experimental,1993-08-16,,',
                ]
            self._releases = [MockDistroRelease(*row.split(',')) for row in data]

        def all(self):
            """List codenames of all known distributions."""
            return [x.series for x in self._releases]

        def valid(self, codename):
            return (codename in self.all()) or (codename in ['unstable', 'testing'])

        def codename(self, release, date=None, default=None):
            if release == 'unstable':
                return 'sid'
            elif release == 'experimental':
                return 'experimental'
            elif not self.valid(codename):
                raise ValueError("Provided codename is not valid for Debian")
            else:
                raise NotImplementedError()

    # Replace the DebianDistroInfo object with our mock,
    # but leave the UbuntuDistroInfo object as-is.
    monkeypatch.setattr(source_information, "_ddi", MockDebianDistroInfo())

    assert derive_codename_from_series(series) == codename


@pytest.mark.parametrize(['debian_input', 'ubuntu_input', 'expected'], [
    (
        [],
        [],
        [],
    ),
    (
        [0],
        [0],
        [(0, 'debian'), (0, 'ubuntu')],
    ),
    (
        [1],
        [0],
        [(0, 'ubuntu'), (1, 'debian')],
    ),
])
def test_interleave_launchpad_versions_published_after(
    debian_input,
    ubuntu_input,
    expected,
):
    """Test that interleaving works correctly

    We will always ask for Debian before Ubuntu. When date_created is the same,
    Debian should come first. If date_created is different, the earlier
    date_created should come first.

    :param list(Any) debian_input: the date_created attributes of the fake
        Launchpad source_package_publishing_history objects of the fake
        GitUbuntuSourcePackageInformation objects that will be returned by the
        faked call to launchpad_versions_published_after() call, for the Debian
        distribution.
    :param list(Any) debian_input: the date_created attributes of the fake
        Launchpad source_package_publishing_history objects of the fake
        GitUbuntuSourcePackageInformation objects that will be returned by the
        faked call to launchpad_versions_published_after() call, for the Ubuntu
        distribution.
    :param list(tuple(date_created, distribution)): the expected ordering in
        the return sequence of the
        interleave_launchpad_versions_published_after() call. date_created
        corresponds to the input data from debian_input and ubuntu_input.
        distribution is either the 'debian' string or the 'ubuntu' string
        depending on whether the return value was supposed to come from the
        Debian or Ubuntu fake GitUbuntuSourceInformation object.
    """
    # Store all fake guspis created, since equivalent guspis will be asserted
    # for equality later, and Mock objects that are otherwise identical do not
    # compare equal if they are separate instances. For the same call to
    # fake_guspi() below, we want to return the same Mock object instance so
    # that they do compare equal.
    fake_guspis = {}
    def fake_guspi(dist_link, date_created):
        """Return a fake target.GitUbuntuSourcePackageInformation object

        Multiple calls to this function with the same parameters return the
        same fake objects so that they compare equal.

        :param Any dist_link: a mock distribution_link that can be compared
            against later (for example, use a unittest.mock.sentinel).
        :param Any date_created: the fake date_created attribute of the
            underlying Launchpad source_package_publishing_history object.
        :rtype: Mock
        :returns: the fake target.GitUbuntuSourcePackageInformation object.
        """
        try:
            return fake_guspis[(dist_link, date_created)]
        except KeyError:
            result = Mock(
                spec=target.GitUbuntuSourcePackageInformation,
                _spphr=Mock(
                    distro_series_link=str(hash(dist_link)) + '_distro_series',
                    distro_series=Mock(distribution_link=dist_link),
                    date_created=date_created,
                )
            )
            fake_guspis[(dist_link, date_created)] = result
            return result

    # A fake target.GitUbuntuSourceInformation object to represent the Debian
    # distribution.
    debian = Mock(
        spec=target.GitUbuntuSourceInformation,
        dist=Mock(self_link=sentinel.debian_dist_link),
        launchpad_versions_published_after=Mock(return_value=[
            fake_guspi(sentinel.debian_dist_link, date_created)
            for date_created in debian_input
        ])
    )
    # A fake target.GitUbuntuSourceInformation object to represent the Ubuntu
    # distribution.
    ubuntu = Mock(
        spec=target.GitUbuntuSourceInformation,
        dist=Mock(self_link=sentinel.ubuntu_dist_link),
        launchpad_versions_published_after=Mock(return_value=[
            fake_guspi(sentinel.ubuntu_dist_link, date_created)
            for date_created in ubuntu_input
        ])
    )

    gusi_head_info_tuple_list = [
        (debian, None),
        (ubuntu, None),
    ]
    result = target.GitUbuntuSourceInformation.interleave_launchpad_versions_published_after(
        gusi_head_info_tuple_list=gusi_head_info_tuple_list,
        namespace=None,
    )
    expanded_result = list(result)
    assert expanded_result == [
        fake_guspi(
            dist_link={
                'debian': sentinel.debian_dist_link,
                'ubuntu': sentinel.ubuntu_dist_link,
            }[dist],
            date_created=date_created,
        )
        for date_created, dist in expected
    ]


@pytest.mark.parametrize(['dist_name', 'input_head_info', 'input_spph'], [
    # Empty case
    (
        'debian', {}, [],
    ),
    # Single publication, nothing imported yet
    (
        'debian',
        {},
        [
            ('sid', '1', 1, True),
        ],
    ),
    # Single publication, already imported
    (
        'debian',
        {'sid': ('1', 1)},
        [
            ('sid', '1', 1, False),
        ],
    ),
    # Two identical publications, nothing imported yet
    (
        'debian',
        {},
        [
            ('sid', '1', 2, True),
            ('bullseye', '1', 1, True),
        ],
    ),
    # Two identical publications, already imported
    (
        'debian',
        {
            'sid': ('1', 1),
            'bullseye': ('1', 1),
        },
        [
            ('sid', '1', 2, True),
            ('bullseye', '1', 1, False),
        ],
    ),
    # Two versions in the normal proposed migration way, one imported
    (
        'debian',
        {
            'sid': ('1', 1),
            'bullseye': ('1', 1),
        },
        [
            ('bullseye', '2', 4, True),
            ('sid', '2', 3, True),
            ('bullseye', '1', 2, True),
            ('sid', '1', 1, False),
        ],
    ),
    # Two versions in the normal proposed migration way, both imported
    (
        'debian',
        {
            'sid': ('2', 3),
            'bullseye': ('2', 3),
        },
        [
            ('bullseye', '2', 4, True),
            ('sid', '2', 3, False),
            ('bullseye', '1', 2, False),
            ('sid', '1', 1, False),
        ],
    ),
    # Empty case
    (
        'ubuntu', {}, [],
    ),
    # Single publication, nothing imported yet
    (
        'ubuntu',
        {},
        [
            ('kinetic-proposed', '1', 1, True),
        ],
    ),
    # Single publication, already imported
    (
        'ubuntu',
        {'kinetic-proposed': ('1', 1)},
        [
            ('kinetic-proposed', '1', 1, False),
        ],
    ),
    # Two identical publications, nothing imported yet
    (
        'ubuntu',
        {},
        [
            ('kinetic', '1', 2, True),
            ('kinetic-proposed', '1', 1, True),
        ],
    ),
    # Two identical publications, already imported
    (
        'ubuntu',
        {
            'kinetic': ('1', 1),
            'kinetic-proposed': ('1', 1),
        },
        [
            ('kinetic', '1', 2, True),
            ('kinetic-proposed', '1', 1, False),
        ],
    ),
    # Two versions in the normal proposed migration way, one imported
    (
        'ubuntu',
        {
            'kinetic-proposed': ('1', 1),
            'kinetic': ('1', 1),
        },
        [
            ('kinetic', '2', 4, True),
            ('kinetic-proposed', '2', 3, True),
            ('kinetic', '1', 2, True),
            ('kinetic-proposed', '1', 1, False),
        ],
    ),
    # Two versions in the normal proposed migration way, both imported
    (
        'ubuntu',
        {
            'kinetic-proposed': ('2', 3),
            'kinetic': ('2', 3),
        },
        [
            ('kinetic', '2', 4, True),
            ('kinetic-proposed', '2', 3, False),
            ('kinetic', '1', 2, False),
            ('kinetic-proposed', '1', 1, False),
        ],
    ),
])
def test_launchpad_versions_published_after(
    dist_name,
    input_head_info,
    input_spph,
):
    """If launchpad_versions_published_after() is shown some particular
    head_info and some set of publications in Launchpad, then it should present
    the expected subset of those publications for import.

    :param str dist_name: either 'debian' or 'ubuntu'
    :param dict input_head_info: a dictionary. Keyed by the branch name without
        any namespace or prefix. The value is a tuple(str, int) of
        (package_version, timestamp).
    :param list input_spph: a list of mock publications from Launchpad in
        reverse chronological order by date_created. Each entry is a 4-tuple
        with the following fields:
            str: the name of the apt suite the publication was made in
            str: the package version string
            int: date_created
            bool: True if this entry should be included in the expected result
    """
    namespaced_input_head_info = {
        f'importer/{dist_name}/{suite}':
            HeadInfoItem(
                version=version,
                commit_time=commit_time,
                commit_id=None,
            )
        for suite, (version, commit_time) in input_head_info.items()
    }

    dist = Mock()
    lp = Mock(distributions={dist_name: dist})
    getPublishedSources = dist.main_archive.getPublishedSources

    getPublishedSources_return_value = []
    for i, (suite, version, date_created, _) in enumerate(input_spph):
        # Create a minimal fake record that would be returned by Launchpad's
        # getPublishedSources method on the Launchpad archive object. We have
        # to do this imperatively in order to set the name attributes
        # (https://docs.python.org/3/library/unittest.mock.html#mock-names-and-the-name-attribute).
        distribution_mock = Mock()
        distribution_mock.name = dist_name
        distro_series_mock = Mock(
            distribution=distribution_mock,
            distribution_link=dist_name,
        )
        distro_series_mock.name = suite.split('-')[0]
        spphr_mock = Mock(
            source_package_version=version,
            date_created=Mock(timestamp=Mock(return_value=date_created)),
            pocket=suite.split('-')[1] if '-' in suite else 'release',
            distro_series=distro_series_mock,
            distro_series_link=suite.split('-')[0],
            test_record_id=i,
        )
        getPublishedSources_return_value.append(spphr_mock)
    getPublishedSources.return_value = getPublishedSources_return_value

    gusi = target.GitUbuntuSourceInformation(
        dist_name=dist_name,
        lp=lp,
        pkgname=sentinel.pkgname,
    )

    actual_result = list(gusi.launchpad_versions_published_after(
        head_info=namespaced_input_head_info,
        namespace='importer',
    ))

    getPublishedSources.assert_called_once_with(
        exact_match=True,
        source_name=sentinel.pkgname,
        order_by_date=True,
    )

    assert list(reversed([
        i
        for i, (_, _, _, expected_in_result) in enumerate(input_spph)
        if expected_in_result
    ])) == [m._spphr.test_record_id for m in actual_result]
