# Copyright 2023 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 blhc task support on the worker."""
import itertools
from pathlib import Path
from unittest import TestCase, mock
from unittest.mock import call

from debusine.artifacts import BlhcArtifact
from debusine.client.models import (
    RemoteArtifact,
)
from debusine.tasks import TaskConfigError
from debusine.tasks.blhc import Blhc
from debusine.tasks.tests.helper_mixin import ExternalTaskHelperMixin
from debusine.test import TestHelpersMixin


class BlhcTaskTests(TestHelpersMixin, ExternalTaskHelperMixin[Blhc], TestCase):
    """Test the Blhc Task class."""

    SAMPLE_TASK_DATA = {
        "input": {"artifact_id": 421},
    }

    def setUp(self):  # noqa: D102
        self.task = Blhc(self.SAMPLE_TASK_DATA)

    def tearDown(self):
        """Delete directory to avoid ResourceWarning with python -m unittest."""
        if self.task._debug_log_files_directory is not None:
            self.task._debug_log_files_directory.cleanup()

    def test_configure_fails_with_missing_required_data(self):  # noqa: D102
        with self.assertRaises(TaskConfigError):
            self.configure_task(override={"input": {}})

    def test_configure_with_extra_flag(self):
        """Configuration included "extra_flags". Saved, no exceptions."""
        extra_flags = ["--bindnow"]

        directory = self.create_temporary_directory()
        (directory / "file.build").write_text("")

        self.configure_task(override={"extra_flags": extra_flags})

        self.patch_prepare_executor_instance()

        self.assertEqual(self.task.data.extra_flags, extra_flags)

        self.assertTrue(self.task.configure_for_execution(directory))

    def test_configure_with_invalid_flag(self):
        """Configuration included "extra_flags". Saved, no exceptions."""
        extra_flags = ["--unknown-flag"]

        directory = self.create_temporary_directory()
        (directory / "file.build").write_text("")

        with self.assertRaises(TaskConfigError):
            self.configure_task(override={"extra_flags": extra_flags})

    def test_configure_additional_properties_in_input(self):
        """Assert no additional properties in task_data input."""
        error_msg = "extra fields not permitted"
        with self.assertRaisesRegex(TaskConfigError, error_msg):
            self.configure_task(
                task_data={
                    "input": {
                        "artifact_id": 5,
                        "some_additional_property": 87,
                    }
                }
            )

    def test_configure_for_execution_from_artifact_id_error_no_build_logs(self):
        """configure_for_execution() no .build files: return False."""
        self.patch_prepare_executor_instance()
        download_directory = self.create_temporary_directory()
        (file1 := download_directory / "file1.dsc").write_text("")
        (file2 := download_directory / "file2.changes").write_text("")

        self.assertFalse(self.task.configure_for_execution(download_directory))

        files = sorted([str(file1), str(file2)])
        log_file_contents = (
            Path(self.task._debug_log_files_directory.name)
            / "configure_for_execution.log"
        ).read_text()
        self.assertEqual(
            log_file_contents,
            f"No *.build files to be analyzed. Files: {files}\n",
        )

    def test_cmdline_with_extra_flags(self):
        """Cmdline add extra_flags."""
        extra_flags = ["--bindnow"]
        self.configure_task(override={"extra_flags": extra_flags})
        self.task._blhc_target = [self.create_temporary_file()]

        cmdline = self.task._cmdline()

        self.assertIn(extra_flags[0], cmdline)
        self.assertEqual(cmdline[-1], str(self.task._blhc_target))

    def test_run_cmd_succeeded(self):
        """run_cmd_succeeded returns True if there's a regular exit status."""
        self.assertTrue(self.task.run_cmd_succeeded(0))
        self.assertTrue(self.task.run_cmd_succeeded(1))
        self.assertFalse(self.task.run_cmd_succeeded(None))

    def test_task_succeeded_empty_file_return_true(self):
        """task_succeeded() for an empty file return True."""
        directory = self.create_temporary_directory()
        (directory / Blhc.CAPTURE_OUTPUT_FILENAME).write_text("")

        self.configure_task()
        self.assertTrue(self.task.task_succeeded(0, directory))

    def test_upload_artifacts(self):
        """upload_artifact() and relation_create() is called."""
        exec_dir = self.create_temporary_directory()

        # Create file that will be attached when uploading the artifacts
        blhc_output = exec_dir / self.task.CAPTURE_OUTPUT_FILENAME
        blhc_output.write_text("NONVERBOSE BUILD:    Compiling gkrust\n")

        # Used to verify the relations
        self.task._source_artifacts_ids = [1]

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

        workspace_name = "testing"

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

        debusine_mock.upload_artifact.side_effect = uploaded_artifacts

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

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

        self.task.upload_artifacts(exec_dir, execution_success=True)

        # Debusine Mock upload_artifact expected calls
        upload_artifact_calls = []
        blhc_artifact = BlhcArtifact.create(blhc_output=blhc_output)

        upload_artifact_calls.append(
            call(
                blhc_artifact,
                workspace=workspace_name,
                work_request=work_request,
            )
        )

        # Debusine mock relation_create expected calls
        relation_create_calls = []
        for uploaded_artifact, source_artifact_id in itertools.product(
            uploaded_artifacts, self.task._source_artifacts_ids
        ):
            relation_create_calls.append(
                call(uploaded_artifact.id, source_artifact_id, "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)

    def test_execute(self):
        """Test full (mocked) execution."""
        # Full execution
        self.configure_task(override={"input": {'artifact_id': 1}})
        download_directory = self.create_temporary_directory()

        with mock.patch.object(
            self.task, "fetch_artifact", autospec=True, return_value=True
        ) as mocked:
            self.assertTrue(self.task.fetch_input(download_directory))
            mocked.assert_any_call(1, download_directory)

        f1_contents = "Compiling gkrust v0.1.0 (/build/rust)"
        (file1 := download_directory / "file.build").write_text(f1_contents)

        self.patch_prepare_executor_instance()

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

        self.assertEqual(self.task._blhc_target, file1)
        self.assertEqual(
            self.task._cmdline(),
            [
                "blhc",
                "--debian",
                str(file1),
            ],
        )

        # Create file that will be attached when uploading the artifacts
        blhc_output = download_directory / self.task.CAPTURE_OUTPUT_FILENAME
        blhc_output.write_text(
            "NONVERBOSE BUILD:    Compiling gkrust v0.1.0 (/build/rust)\n"
        )

        with mock.patch.object(
            self.task, "upload_artifacts", autospec=True
        ) as mocked:
            self.assertTrue(
                self.task.upload_artifacts(
                    download_directory, execution_success=True
                )
            )
