# Copyright © The Debusine Developers
# See the AUTHORS file at the top-level directory of this distribution
#
# This file is part of Debusine. It is subject to the license terms
# in the LICENSE file found in the top-level directory of this
# distribution. No part of Debusine, including this file, may be copied,
# modified, propagated, or distributed except according to the terms
# contained in the LICENSE file.

"""Unit tests for the makesourcepackageupload task support on the worker."""

from pathlib import Path
from typing import override
from unittest import mock
from unittest.mock import call

import debusine.tasks.tags as ttags
import debusine.worker.tags as wtags
from debusine.artifacts import Upload
from debusine.artifacts.models import (
    ArtifactCategory,
    DebianSourcePackage,
    WorkRequestResults,
)
from debusine.client.models import LookupResultType, LookupSingleResponse
from debusine.tasks import MakeSourcePackageUpload, TaskConfigError
from debusine.tasks.models import MakeSourcePackageUploadDynamicData
from debusine.tasks.tests.helpers import ExternalTaskHelperMixin
from debusine.test import TestCase
from debusine.test.test_utils import (
    create_artifact_response,
    create_remote_artifact,
    create_system_tarball_data,
)


class MakeSourcePackageUploadTests(
    ExternalTaskHelperMixin[MakeSourcePackageUpload], TestCase
):
    """Test the MakeSourcePackageUpload class."""

    SAMPLE_TASK_DATA = {
        "environment": "debian/match:codename=bookworm",
        "input": {"source_artifact": 421},
    }

    @override
    def setUp(self) -> None:
        super().setUp()
        self.resolver.set_field_artifact(
            "environment",
            id=1,
            category=ArtifactCategory.SYSTEM_TARBALL,
            data=create_system_tarball_data(),
        )
        self.resolver.set_field_artifact(
            "input_source_artifact",
            id=421,
            category=ArtifactCategory.SOURCE_PACKAGE,
            data=DebianSourcePackage(
                name="hello", version="1.0", type="dpkg", dsc_fields={}
            ),
        )

    def test_get_provided_worker_tags(self) -> None:
        self.assertCountEqual(
            self.task.get_provided_worker_tags(),
            [
                wtags.TASK_PREFIX + "worker:makesourcepackageupload:version:1",
            ],
        )

    def test_compute_scheduler_tags(self) -> None:
        self.assertComputesSchedulerTags(
            provide_system={ttags.SOURCE_PACKAGE_PREFIX + "hello"},
            require_system={
                wtags.BUILD_ARCH_PREFIX + "amd64",
                wtags.EXECUTOR_PREFIX + "unshare",
            },
        )

    def test_compute_dynamic_data(self) -> None:
        """Dynamic data receives relevant artifact IDs."""
        self.assertEqual(
            self.compute_dynamic_data(self.task),
            MakeSourcePackageUploadDynamicData(
                environment_id=1,
                input_source_artifact_id=421,
                subject="hello",
                parameter_summary="hello_1.0",
            ),
        )

    def test_get_subject(self) -> None:
        self.assertEqual(self.get_subject(), "hello")

    def test_get_configuration_context(self) -> None:
        self.assertIsNone(self.get_configuration_context())

    def test_acceptable_input_categories(self) -> None:
        self.assertEqual(
            MakeSourcePackageUpload.inputs["input_source_artifact"].categories,  # type: ignore[attr-defined]
            (ArtifactCategory.SOURCE_PACKAGE,),
        )

    def test_get_input_artifacts_ids(self) -> None:
        """Test get_input_artifacts_ids."""
        self.assertEqual(self.task.get_input_artifacts_ids(), [])

        self.task.dynamic_data = MakeSourcePackageUploadDynamicData(
            environment_id=1,
            input_source_artifact_id=2,
        )
        self.assertEqual(self.task.get_input_artifacts_ids(), [1, 2])

    def test_configure_fails_with_missing_required_data(
        self,
    ) -> None:
        with self.assertRaises(TaskConfigError):
            self.configure_task(override={"input": {}})

    def test_fetch_input(self) -> None:
        """Test fetch_input: call fetch_artifact(artifact_id, directory)."""
        directory = self.create_temporary_directory()
        source_artifact = self.fake_debian_source_package_artifact()
        self.configure_task()
        self.task.work_request_id = 5
        self.task.dynamic_data = MakeSourcePackageUploadDynamicData(
            environment_id=1, input_source_artifact_id=source_artifact.id
        )
        debusine_mock = self.mock_debusine()
        debusine_mock.artifact_get.return_value = source_artifact

        with mock.patch.object(
            self.task, "fetch_artifact", autospec=True, return_value=True
        ) as fetch_artifact_mocked:
            result = self.task.fetch_input(directory)

        self.assertTrue(result)
        fetch_artifact_mocked.assert_called_once_with(
            source_artifact.id, directory
        )

    def test_fetch_input_wrong_category(self) -> None:
        """Test fetch_input when input isn't a source package."""
        directory = self.create_temporary_directory()
        source_artifact = create_artifact_response(id=12)
        self.configure_task()
        self.task.work_request_id = 5
        self.task.dynamic_data = MakeSourcePackageUploadDynamicData(
            environment_id=1, input_source_artifact_id=source_artifact.id
        )
        debusine_mock = self.mock_debusine()
        debusine_mock.artifact_get.return_value = source_artifact

        with mock.patch.object(
            self.task, "fetch_artifact", autospec=True
        ) as fetch_artifact_mocked:
            result = self.task.fetch_input(directory)

        self.assertFalse(result)

        log_file_contents = (
            self.task.log_directory / "fetch_input.log"
        ).read_text()
        self.assertEqual(
            log_file_contents,
            (
                "input.source_artifact points to a Testing, not the "
                "expected debian:source-package.\n"
            ),
        )

        fetch_artifact_mocked.assert_not_called()

    def test_configure_for_execution(self) -> None:
        """configure_for_execution installs dependencies."""
        download_directory = self.create_temporary_directory()
        (download_directory / "file.dsc").touch()
        mocked_prepare_executor_instance = (
            self.patch_prepare_executor_instance()
        )

        self.assertTrue(self.task.configure_for_execution(download_directory))

        mocked_prepare_executor_instance.assert_called_once_with()
        assert isinstance(self.task.executor_instance, mock.MagicMock)
        self.task.executor_instance.assert_has_calls(
            [
                mock.call.run(
                    ["apt-get", "update"], run_as_root=True, check=True
                ),
                mock.call.run(
                    ["apt-get", "--yes", "install", "dpkg-dev"],
                    run_as_root=True,
                    check=True,
                ),
            ]
        )

    def test_execute(self) -> None:
        """Test full (mocked) execution."""
        self.configure_task()
        self.task.work_request_id = 2
        self.task.workspace_name = "testing"
        self.task.dynamic_data = MakeSourcePackageUploadDynamicData(
            environment_id=1, input_source_artifact_id=1
        )
        download_directory = self.create_temporary_directory()

        debusine_mock = self.mock_debusine()
        debusine_mock.lookup_single.return_value = LookupSingleResponse(
            result_type=LookupResultType.ARTIFACT, artifact=1
        )
        debusine_mock.download_artifact.return_value = True
        debusine_mock.upload_artifact.return_value = create_remote_artifact(
            id=2, workspace=self.task.workspace_name
        )

        f_in_contents = "Format: 3.0 (quilt)"
        (f_in := download_directory / "file.dsc").write_text(f_in_contents)
        (f_out := download_directory / "file_source.changes")
        self.write_changes_file(f_out, [f_in])

        self.patch_prepare_executor_instance()

        self.assertTrue(self.task.configure_for_execution(download_directory))

        self.assertEqual(self.task._dsc_path, f_in)
        self.assertEqual(
            self.task._cmdline(),
            [
                "bash",
                "-x",
                "-e",
                str(download_directory / "makesourcepackageupload.sh"),
                str(f_in),
                str(f_out),
                '',
                '',
            ],
        )

        self.task.upload_artifacts(
            download_directory, execution_result=WorkRequestResults.SUCCESS
        )

        debusine_mock.upload_artifact.assert_called_once_with(
            Upload.create(changes_file=f_out),
            workspace=self.task.workspace_name,
            work_request=self.task.work_request_id,
        )
        debusine_mock.relation_create.assert_has_calls(
            [mock.call(2, 1, "extends"), mock.call(2, 1, "relates-to")]
        )

    def test_optional_arguments(self) -> None:
        """Test optional arguments."""
        self.configure_task(override={"since_version": "2.10-1~"})
        self.task._shell_script = Path("script")
        self.task._dsc_path = Path("in")
        self.task._changes_path = Path("out")
        expected = ["bash", "-x", "-e", "script", "in", "out"]
        self.assertEqual(
            self.task._cmdline(),
            [*expected, "2.10-1~", ""],
        )

        self.configure_task(
            override={"target_distribution": "bullseye-security"}
        )
        self.task._shell_script = Path("script")
        self.task._dsc_path = Path("in")
        self.task._changes_path = Path("out")
        self.assertEqual(
            self.task._cmdline(),
            [*expected, "", "bullseye-security"],
        )

        self.configure_task(
            override={
                "since_version": "1 0",
                "target_distribution": "buster elts",
            }
        )
        self.task._shell_script = Path("script")
        self.task._dsc_path = Path("in")
        self.task._changes_path = Path("out")
        self.assertEqual(
            self.task._cmdline(),
            [*expected, "1 0", "buster elts"],
        )

    def test_upload_artifacts(self) -> None:
        """upload_artifact() and relation_create() is called."""
        self.task.dynamic_data = MakeSourcePackageUploadDynamicData(
            environment_id=1, input_source_artifact_id=1
        )
        download_directory = self.create_temporary_directory()

        # Create file that will be attached when uploading the artifacts
        f_in_contents = "Format: 3.0 (quilt)"
        (f_in := download_directory / "file.dsc").write_text(f_in_contents)
        (f_out := download_directory / "file_source.changes")
        self.write_changes_file(f_out, [f_in])
        self.task._changes_path = f_out

        # Debusine.upload_artifact is mocked to verify the call only
        debusine_mock = self.mock_debusine()

        workspace_name = "testing"

        uploaded_artifacts = [
            create_remote_artifact(id=10, workspace=workspace_name),
        ]

        debusine_mock.upload_artifact.side_effect = uploaded_artifacts

        # self.task.workspace_name is set by the Worker
        # and is the workspace that downloads the artifact
        # containing the files needed for MakeSourcePackageUpload
        self.task.workspace_name = workspace_name

        # The worker set self.task.work_request_id of the task
        work_request_id = 147
        self.task.work_request_id = work_request_id

        with mock.patch.object(self.task, "executor_instance", autospec=True):
            self.task.upload_artifacts(
                download_directory, execution_result=WorkRequestResults.SUCCESS
            )

        # Debusine Mock upload_artifact expected calls
        upload_artifact_calls = []
        makesourcepackageupload_artifact = Upload.create(changes_file=f_out)

        upload_artifact_calls.append(
            call(
                makesourcepackageupload_artifact,
                workspace=workspace_name,
                work_request=work_request_id,
            )
        )

        # Debusine mock relation_create expected calls
        relation_create_calls = []
        relation_create_calls.append(
            call(uploaded_artifacts[0].id, 1, "relates-to")
        )

        # Assert that the artifacts were uploaded and relations created
        debusine_mock.upload_artifact.assert_has_calls(upload_artifact_calls)
        debusine_mock.relation_create.assert_has_calls(relation_create_calls)
