import re
import sys
import unittest.mock
from unittest.mock import patch

import pygit2
import pytest

from gitubuntu.git_repository import GitUbuntuRepository
from gitubuntu.repo_builder import Commit, Placeholder, Repo
from gitubuntu.test_fixtures import repo, pygit2_repo

import gitubuntu.prepare_upload as target


@pytest.fixture
def populated_repo(repo):
    """A pytest fixture that provides a GitUbuntuRepository populated with
    suitable data for the purposes of the tests in this module"""
    Repo(
        commits=[
            Commit(name='main', message='main'),
            Commit(name='other', message='other'),
        ],
        branches={
            'main': Placeholder('main'),
            'other': Placeholder('other'),
        },
    ).write(repo.raw_repo)
    repo.raw_repo.checkout('refs/heads/main')
    yield repo


def test_establish_args_with_branch(populated_repo):
    """Pushes and outputs correct fields when a branch name is specified

    :param GitUbuntuRepository populated_repo: fixture providing a temporary
        GitUbuntuRepository populated with our standard test data.
    """
    repo = populated_repo

    repo.raw_repo.remotes.create(
        'testremote',
        'https://git.launchpad.net/test',
    )

    with patch.object(repo, 'git_run') as mock_run:
        result = target.establish_args(
            repo=repo,
            remote_name='testremote',
            branch_name='other',
        )
        mock_run.assert_called_with(
            [
                'push',
                'testremote',
                'refs/heads/other:refs/heads/other',
            ],
            stdout=unittest.mock.ANY,
            stderr=None,
        )

    other_ref = repo.raw_repo.lookup_reference('refs/heads/other')
    commit_hash = other_ref.peel(pygit2.Commit).id
    expected_result = {
        'Vcs-Git': 'https://git.launchpad.net/test',
        'Vcs-Git-Ref': 'refs/heads/other',
        'Vcs-Git-Commit': str(commit_hash),
    }
    assert result.changes_file_headers == expected_result


def test_establish_args_without_branch(populated_repo):
    """Pushes and outputs correct fields when no branch is specified

    :param GitUbuntuRepository populated_repo: fixture providing a temporary
        GitUbuntuRepository populated with our standard test data.
    """
    repo = populated_repo

    repo.raw_repo.checkout('refs/heads/other')
    repo.raw_repo.remotes.create(
        'testremote',
        'https://git.launchpad.net/test',
    )

    with patch.object(repo, 'git_run') as mock_run:
        result = target.establish_args(repo=repo, remote_name='testremote')
        mock_run.assert_called_with(
            [
                'push',
                'testremote',
                'refs/heads/other:refs/heads/other',
            ],
            stdout=unittest.mock.ANY,
            stderr=None,
        )

    other_ref = repo.raw_repo.lookup_reference('refs/heads/other')
    commit_hash = other_ref.peel(pygit2.Commit).id
    expected_result = {
        'Vcs-Git': 'https://git.launchpad.net/test',
        'Vcs-Git-Ref': 'refs/heads/other',
        'Vcs-Git-Commit': str(commit_hash),
    }
    assert result.changes_file_headers == expected_result


def test_establish_args_without_remote(populated_repo):
    """Pushes and outputs correct fields when no remote is specified

    :param GitUbuntuRepository populated_repo: fixture providing a temporary
        GitUbuntuRepository populated with our standard test data.
    """
    repo = populated_repo
    repo.raw_repo.config['gitubuntu.lpuser'] = 'testuser'

    # Reload GitUbuntuRepository so that lp_user gets read again
    repo = GitUbuntuRepository(repo.raw_repo.workdir)

    repo.raw_repo.remotes.create('testuser', 'https://git.launchpad.net/~test')
    with patch.object(repo, 'git_run') as mock_run:
        result = target.establish_args(repo=repo)
        mock_run.assert_called_with(
            [
                'push',
                'testuser',
                'refs/heads/main:refs/heads/main',
            ],
            stdout=unittest.mock.ANY,
            stderr=None,
        )

    main_ref = repo.raw_repo.lookup_reference('refs/heads/main')
    commit_hash = main_ref.peel(pygit2.Commit).id
    expected_result = {
        'Vcs-Git': 'https://git.launchpad.net/~test',
        'Vcs-Git-Ref': 'refs/heads/main',
        'Vcs-Git-Commit': str(commit_hash),
    }
    assert result.changes_file_headers == expected_result


def test_establish_args_stdout(populated_repo):
    """git push output is written to the terminal

    The user expects to see the output of "git push" on the terminal. However,
    we cannot output to stdout, since that is to be captured for use in command
    line arguments to dpkg-buildpackage or a similar command. So stdout output
    from git must go to stderr, and stderr output must not have been adjusted.

    :param GitUbuntuRepository populated_repo: fixture providing a temporary
        GitUbuntuRepository populated with our standard test data.
    """
    repo = populated_repo
    repo.raw_repo.remotes.create(
        'testremote',
        'https://git.launchpad.net/test',
    )
    with patch.object(repo, 'git_run') as mock_run:
        result = target.establish_args(
            repo=repo,
            remote_name='testremote',
            branch_name='other',
        )
    assert mock_run.call_args.kwargs['stdout'] is sys.stderr
    assert mock_run.call_args.kwargs['stderr'] is None


@patch("builtins.print")
@patch("gitubuntu.prepare_upload.establish_args")
def test_establish_args_failure(
    mock_establish_args,
    mock_print,
    populated_repo,
    monkeypatch,
):
    """On failure, the CLI prints an impossible argument

    :param unittest.mock.Mock mock_establish_args: the mocked out
        establish_args function
    :param unittest.mock.Mock mock_print: the mocked out print function
    :param GitUbuntuRepository populated_repo: fixture providing a temporary
        GitUbuntuRepository populated with our standard test data.
    :param monkeypatch: the standard pytest monkeypatch fixture

    See: LP #1942865
    """
    monkeypatch.chdir(populated_repo.raw_repo.workdir)
    mock_establish_args.side_effect = RuntimeError("Mock failure")
    with pytest.raises(RuntimeError):
        target.cli_printargs(unittest.mock.Mock(
            remote=None,
            branch=None,
            output_format="dpkg-buildpackage",
        ))
    mock_print.assert_called_once_with(
        "--git-ubuntu-prepare-upload-args-failed",
    )


@pytest.mark.parametrize(['remote_url'], [
    ('git+ssh://user@git.launchpad.net/test',),
    ('ssh://user@git.launchpad.net/test',),
])
def test_establish_args_rewrites_lp_ssh_url(populated_repo, remote_url):
    """Rewrites Vcs-Git: to an https: one when git+ssh: or ssh: is used with LP

    See LP: #1942985

    :param GitUbuntuRepository populated_repo: fixture providing a temporary
        GitUbuntuRepository populated with our standard test data.
    :param str remote_url: the URL that we will test is rewritten
    """
    repo = populated_repo
    repo.raw_repo.remotes.create('testremote', remote_url)
    with patch.object(repo, 'git_run') as mock_run:
        result = target.establish_args(
            repo=repo,
            remote_name='testremote',
            branch_name='other',
        )
        mock_run.assert_called_with(
            [
                'push',
                'testremote',
                'refs/heads/other:refs/heads/other',
            ],
            stdout=unittest.mock.ANY,
            stderr=None,
        )

    other_ref = repo.raw_repo.lookup_reference('refs/heads/other')
    commit_hash = other_ref.peel(pygit2.Commit).id
    expected_result = {
        'Vcs-Git': 'https://git.launchpad.net/test',
        'Vcs-Git-Ref': 'refs/heads/other',
        'Vcs-Git-Commit': str(commit_hash),
    }
    assert result.changes_file_headers == expected_result


FAKE_SIGNED_CHANGES_FILE = """-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA512

Format: 1.8
Source: test

-----BEGIN PGP SIGNATURE-----

Fake signature data
-----END PGP SIGNATURE-----
"""
@pytest.fixture
def fake_changes_file_path(tmpdir):
    """A fixture to provide a fake changes file ready for mangling

    This fixture does no cleanup on the assumption that the automatic cleanup
    of the tmpdir fixture it uses is sufficient.

    :param tmpdir: the standard pytest tmpdir fixture
    :rtype: str
    :returns: the path to our standard fake changes file in a temporary
        directory
    """
    changes_file_path = str(tmpdir.join('changes'))
    with open(changes_file_path, 'w') as f:
        f.write(FAKE_SIGNED_CHANGES_FILE)
    return changes_file_path


def test_mangle_changes(populated_repo, fake_changes_file_path):
    """Pushes and adds correct fields

    :param GitUbuntuRepository populated_repo: fixture providing a temporary
        GitUbuntuRepository populated with our standard test data.
    :param str fake_changes_file_path: our test changes file fixture
    """
    repo = populated_repo

    repo.raw_repo.checkout('refs/heads/other')
    repo.raw_repo.remotes.create(
        'testremote',
        'https://git.launchpad.net/test',
    )

    with patch.object(repo, 'git_run') as mock_run:
        target.mangle_changes(
            repo=repo,
            remote_name='testremote',
            branch_name='main',
            changes_file_path=fake_changes_file_path,
        )
        mock_run.assert_called_with(
            [
                'push',
                'testremote',
                'refs/heads/main:refs/heads/main',
            ],
            stdout=unittest.mock.ANY,
            stderr=None,
        )

    main_ref = repo.raw_repo.lookup_reference('refs/heads/main')
    commit_hash = main_ref.peel(pygit2.Commit).id
    expected_result = {
        'vcs_git': 'https://git.launchpad.net/test',
        'vcs_git_ref': 'refs/heads/main',
        'vcs_git_commit': str(commit_hash),
    }
    with open(fake_changes_file_path, 'r') as f:
        data = f.read()
    assert sorted(data.splitlines()) == [
        "Format: 1.8",
        "Source: test",
        f"Vcs-Git-Commit: {commit_hash!s}",
        "Vcs-Git-Ref: refs/heads/main",
        "Vcs-Git: https://git.launchpad.net/test",
    ]


def test_mod_changes_file(fake_changes_file_path):
    """mod_changes_file mangles our standard fake changes file as expected

    Note that this includes stripping of the signature.

    :param str fake_changes_file_path: our test changes file fixture
    """
    target.mod_changes_file(
        changes_file_path=fake_changes_file_path,
        replacements={'Added': 'yes'},
    )
    with open(fake_changes_file_path, 'r') as f:
        data = f.read()
    assert data == "Format: 1.8\nSource: test\nAdded: yes\n"


def test_mod_changes_file_idempotent(fake_changes_file_path):
    """mangle_changes operates idempotently

    If run twice, the output should still be as expected. Note that this has
    the effect of verifying that it will also work correctly when the changes
    file is unsigned, since that's the result of the first call.

    :param str fake_changes_file_path: our test changes file fixture
    """
    target.mod_changes_file(fake_changes_file_path, {'Added': 'yes'})
    target.mod_changes_file(fake_changes_file_path, {'Added': 'yes'})
    with open(fake_changes_file_path, 'r') as f:
        data = f.read()
    assert data == "Format: 1.8\nSource: test\nAdded: yes\n"


@patch('gitubuntu.importer.LAUNCHPAD_GIT_HOSTING_URL_PREFIX', '')
@patch('gitubuntu.importer.VCS_GIT_URL_VALIDATION', re.compile(r'.*'))
def test_fetch_gets_called(populated_repo, pygit2_repo):
    """We fetch from the repository during a establish_args operation

    :param GitUbuntuRepository populated_repo: fixture providing a temporary
        GitUbuntuRepository populated with our standard test data.
    :param pygit.Repository pygit2_repo: our empty pygit2 repository fixture.
    """
    # Note that we cannot use a repo instance twice, even if one is via
    # populated_repo, because pytest will give us only one instance. A
    # convenient workaround is that the remote repo doesn't need to be a
    # GitUbuntuRepository and so the pygit2_repo fixture will do as it is
    # independent. We can assert they are definitely different:
    assert populated_repo.raw_repo is not pygit2_repo

    remote_repo = pygit2_repo
    local_repo = populated_repo

    # Allow the push even for our non-bare "remote" test repo
    pygit2_repo.config['receive.denyCurrentBranch'] = 'ignore'

    local_repo.raw_repo.remotes.create('test-remote', pygit2_repo.path)
    local_repo.git_run(["push", "test-remote", "main"])

    with patch.object(local_repo, 'git_run') as mock_run:
        target.establish_args(
            repo=local_repo,
            remote_name='test-remote',
            branch_name='main',
        )
    mock_run.assert_called_with(
        ['fetch', 'test-remote'],
        stdout=unittest.mock.ANY,
        stderr=None,
        env=unittest.mock.ANY,
        check=False,
        verbose_on_failure=False,
    )


@patch('gitubuntu.importer.LAUNCHPAD_GIT_HOSTING_URL_PREFIX', '')
@patch('gitubuntu.importer.VCS_GIT_URL_VALIDATION', re.compile(r'.*'))
def test_no_push_when_already_present(populated_repo, pygit2_repo):
    """If the rich history is already available, we do not try to push again

    :param GitUbuntuRepository populated_repo: fixture providing a temporary
        GitUbuntuRepository populated with our standard test data.
    :param pygit.Repository pygit2_repo: our empty pygit2 repository fixture.
    """
    # Note that we cannot use a repo instance twice, even if one is via
    # populated_repo, because pytest will give us only one instance. A
    # convenient workaround is that the remote repo doesn't need to be a
    # GitUbuntuRepository and so the pygit2_repo fixture will do as it is
    # independent. We can assert they are definitely different:
    assert populated_repo.raw_repo is not pygit2_repo

    remote_repo = pygit2_repo
    local_repo = populated_repo

    # Allow the push even for our non-bare "remote" test repo
    pygit2_repo.config['receive.denyCurrentBranch'] = 'ignore'

    local_repo.raw_repo.remotes.create('test-remote', pygit2_repo.path)
    local_repo.git_run(["push", "test-remote", "main"])

    with patch.object(target, 'push') as mock_push:
        target.establish_args(
            repo=local_repo,
            remote_name='test-remote',
            branch_name='main',
        )
        mock_push.assert_not_called()


@patch('gitubuntu.importer.LAUNCHPAD_GIT_HOSTING_URL_PREFIX', '')
@patch('gitubuntu.importer.VCS_GIT_URL_VALIDATION', re.compile(r'.*'))
def test_rejects_force_push(populated_repo, pygit2_repo):
    """If the remote branch cannot be fast-forwarded and we didn't request a
    force push, then an exception is raised

    :param GitUbuntuRepository populated_repo: fixture providing a temporary
        GitUbuntuRepository populated with our standard test data.
    :param pygit.Repository pygit2_repo: our empty pygit2 repository fixture.
    """
    # Note that we cannot use a repo instance twice, even if one is via
    # populated_repo, because pytest will give us only one instance. A
    # convenient workaround is that the remote repo doesn't need to be a
    # GitUbuntuRepository and so the pygit2_repo fixture will do as it is
    # independent. We can assert they are definitely different:
    assert populated_repo.raw_repo is not pygit2_repo

    remote_repo = pygit2_repo
    local_repo = populated_repo

    # Write something to the remote main branch so it cannot be fast-forwarded
    # with what we have locally
    Repo(
        commits=[
            Commit(name='main', message='mutated'),
        ],
        branches={
            'main': Placeholder('main'),
        },
    ).write(remote_repo)

    local_repo.raw_repo.remotes.create('test-remote', pygit2_repo.path)

    with pytest.raises(target.ForcePushRequired):
        target.establish_args(
            repo=local_repo,
            remote_name='test-remote',
            branch_name='main',
        )


@patch('gitubuntu.importer.LAUNCHPAD_GIT_HOSTING_URL_PREFIX', '')
@patch('gitubuntu.importer.VCS_GIT_URL_VALIDATION', re.compile(r'.*'))
def test_performs_force_push(populated_repo, pygit2_repo):
    """If the remote branch cannot be fast-forwarded and we did request a force
    push, then the remote branch is updated

    :param GitUbuntuRepository populated_repo: fixture providing a temporary
        GitUbuntuRepository populated with our standard test data.
    :param pygit.Repository pygit2_repo: our empty pygit2 repository fixture.
    """
    # Note that we cannot use a repo instance twice, even if one is via
    # populated_repo, because pytest will give us only one instance. A
    # convenient workaround is that the remote repo doesn't need to be a
    # GitUbuntuRepository and so the pygit2_repo fixture will do as it is
    # independent. We can assert they are definitely different:
    assert populated_repo.raw_repo is not pygit2_repo

    remote_repo = pygit2_repo
    local_repo = populated_repo

    # Write something to the remote main branch so it cannot be fast-forwarded
    # with what we have locally
    Repo(
        commits=[
            Commit(name='main', message='mutated'),
        ],
        branches={
            'main': Placeholder('main'),
        },
    ).write(remote_repo)

    # Allow the push even for our non-bare "remote" test repo
    pygit2_repo.config['receive.denyCurrentBranch'] = 'ignore'

    local_repo.raw_repo.remotes.create('test-remote', pygit2_repo.path)

    target.establish_args(
        repo=local_repo,
        remote_name='test-remote',
        branch_name='main',
        force_push=True,
    )

    local_commit_id = (
        populated_repo.raw_repo.references["refs/heads/main"]
        .peel(pygit2.Commit)
        .id
    )
    remote_commit_id = (
        pygit2_repo.references["refs/heads/main"].peel(pygit2.Commit).id
    )
    assert local_commit_id == remote_commit_id
